压缩目录并上传到 FTP 服务器,而无需在 C# 中本地保存 .zip 文件 [英] Zip a directory and upload to FTP server without saving the .zip file locally in C#

查看:21
本文介绍了压缩目录并上传到 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.

基于:

这篇关于压缩目录并上传到 FTP 服务器,而无需在 C# 中本地保存 .zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆