压缩目录并上传到FTP服务器而不在C#中本地保存.zip文件

时间:2017-10-11 08:06:16

标签: c# .net ftp upload zip

嘿伙计们,我的问题是标题。我试过这个:

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\to\zip";
    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:&#34;不支持路径格式。&#34;

我不知道在这种情况下我应该如何连接到FTP服务器并压缩ram中的目录并将其直接发送到服务器。

......有人可以帮助或链接到类似或同等问题的解决方案吗?

2 个答案:

答案 0 :(得分:2)

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文件保存在内存中。

基于:

答案 1 :(得分:1)

像这样的东西可以使ZIP进入内存:

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();
    }
}

获得字节数组后,您应该可以随时将其发送到服务器。