Zip a directory and upload to FTP server without saving the .zip file locally in C#(压缩目录并上传到 FTP 服务器,而无需在 C# 中本地保存 .zip 文件)
问题描述
我的问题是标题.我试过这个:
My question is the title. I have tried this:
public void UploadToFtp(List<strucProduktdaten> ProductData)
{
ProductData.ForEach(delegate( strucProduktdaten data )
{
ZipFile.CreateFromDirectory(data.Quellpfad, data.Zielpfad, CompressionLevel.Fastest, true);
});
}
static void Main(string[] args)
{
List<strucProduktdaten> ProductDataList = new List<strucProduktdaten>();
strucProduktdaten ProduktData = new strucProduktdaten();
ProduktData.Quellpfad = @"Path ozip";
ProduktData.Zielpfad = @"Link to the ftp"; // <- i know the link makes no sense without a connect to the ftp with uname and password
ProductDataList.Add(ProduktData);
ftpClient.UploadToFtp(ProductDataList);
}
错误:
System.NotSupportedException:不支持路径格式."
System.NotSupportedException:"The Path format is not supported."
我不知道在这种情况下我应该如何连接到 FTP 服务器并将目录压缩到 ram 中并将其直接发送到服务器.
I have no idea how I should connect in this case to the FTP server and zipping the directory in ram and send it directly to the server.
...有人可以提供帮助或提供指向类似或相同问题的链接吗?解决了什么?
... can someone help or have a link to a similar or equal problem what was solved?
推荐答案
在MemoryStream中创建ZIP压缩包并上传.
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:sourcedirectory"))
{
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);
var request =
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 文件保存在内存中.
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.
基于:
- 使用 System.IO.Compression 在内存中创建 ZIP 存档
- 将文件从字符串或流上传到 FTP 服务器
这篇关于压缩目录并上传到 FTP 服务器,而无需在 C# 中本地保存 .zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:压缩目录并上传到 FTP 服务器,而无需在 C# 中本
基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
