【问题标题】:ZipFile.CreateFromDirectory C# send to MemoryStreamZipFile.CreateFromDirectory C# 发送到 MemoryStream
【发布时间】:2018-10-17 16:29:12
【问题描述】:

我将如何基本上使用ZipFile.CreateFromDirectory 将 zipfile 发送回内存流而不是输出路径。

或者我必须使用ZipArchive 并自己生成 zip 文件吗?似乎有点奇怪,没有流的方法。

这基本上就是我想要做的事情

using (MemoryStream ms = new MemoryStream())
{
   ZipFile.CreateFromDirectory(path, ms)
   buf = ms.ToArray();
   LogZipFile(path, filesize, buf.LongLength);
}

【问题讨论】:

标签: c# c#-4.0


【解决方案1】:

我基于这个https://stackoverflow.com/a/17939367/12634387实现它

public static class FileExtensions
   {
    public static IEnumerable<FileSystemInfo> AllFilesAndFolders(this DirectoryInfo dir)
    {
        foreach (var f in dir.GetFiles())
            yield return f;
        foreach (var d in dir.GetDirectories())
        {
            yield return d;
            foreach (var o in AllFilesAndFolders(d))
                yield return o;
        }
     }
   }
 public static byte[] ZipFolders(string folderPath)
    {
        if (Directory.Exists(folderPath))
        {
            DirectoryInfo from = new DirectoryInfo(folderPath);
            using (var zipToOpen = new MemoryStream())
            {
                using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                {
                    foreach (var file in from.AllFilesAndFolders().OfType<FileInfo>())
                    {
                        var relPath = file.FullName.Substring(from.FullName.Length + 1);
                        ZipArchiveEntry readmeEntry = archive.CreateEntryFromFile(file.FullName, relPath);
                    }
                }
                return zipToOpen.ToArray();
            }
        }
        else
        {
            return null;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多