Zip a directory and upload to FTP server without saving the .zip file locally in C#

↘锁芯ラ 提交于 2019-12-06 03:05:14

Create the ZIP archive in MemoryStream and upload it.

using (Stream memoryStream = new MemoryStream())
{
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
        foreach (string path in Directory.EnumerateFiles(@"C:\source\directory"))
        {
            ZipArchiveEntry entry = archive.CreateEntry(Path.GetFileName(path));

            using (Stream entryStream = entry.Open())
            using (Stream fileStream = File.OpenRead(path))
            {
                fileStream.CopyTo(entryStream);
            }
        }
    }

    memoryStream.Seek(0, SeekOrigin.Begin);

    FtpWebRequest request =
        (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/archive.zip");
    request.Credentials = new NetworkCredential("username", "password");
    request.Method = WebRequestMethods.Ftp.UploadFile;
    using (Stream ftpStream = request.GetRequestStream())
    {
        memoryStream.CopyTo(ftpStream);
    }
}

Unfortunately the ZipArchive requires a seekable stream. Were it not, you would be able to write directly to the FTP request stream and won't need to keep a whole ZIP file in a memory.


Based on:

Something like this would work as far as getting the ZIP into memory goes:

public static byte[] ZipFolderToMemory(string folder)
{
    using (var stream = new MemoryStream())
    {
        using (var archive = new ZipArchive(stream, ZipArchiveMode.Create))
        {
            foreach (var filePath in Directory.EnumerateFiles(folder))
            {
                var entry = archive.CreateEntry(Path.GetFileName(filePath));

                using (var zipEntry = entry.Open())
                using (var file = new FileStream(filePath, FileMode.Open))
                {
                    file.CopyTo(zipEntry);
                }
            }
        }

        return stream.ToArray();
    }
}

Once you have the byte array, you should readily be able to send it to the server.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!