在MemoryStream中创建ZIP存档并上传。
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);
}
}
不幸的是,ZipArchive需要可搜索的流。如果不是,您将能够直接写入FTP请求流,而不需要将整个ZIP文件保存在内存中。
基于: