ZipArchive使用Zip文件创建条目到内存流

时间:2018-11-02 15:29:12

标签: c# zipfile

我正在使用Zip Archive创建一个包含各种文件和子文件夹的zip文件夹,并像这样将其作为内存流返回。

 public MemoryStream CreateAZipFolder(){

var stMarged = new System.IO.MemoryStream();
 stMarged.Position = 0;
     using (MemoryStream zipStream = new MemoryStream())
            {

                using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
                {
   string[] fileEntries = Directory.GetFiles(@"C:\Applications\folder");
                    foreach (var fileName in fileEntries)
                    {

                        zip.CreateEntryFromFile(fileName, "Applications/folder/" + Path.GetFileName(fileName),
                            CompressionLevel.Optimal);
                    }
    ZipArchiveEntry batchEntry = zip.CreateEntry("mybatchFile.bat");
                    using (StreamWriter writer = new StreamWriter(batchEntry.Open()))
                    {
                        writer.Write(batchFile);
                    }

                    //Add the xml file to zip folder
                    ZipArchiveEntry entry = zip.CreateEntry("nCounterConfig.xml");
                    using (StreamWriter writer = new StreamWriter(entry.Open()))
                    {
                       writer.Write(xdoc.OuterXml);
                    }


                }

                zipStream.Position = 0;
                return zipStream;

我想向该内存流添加一个包含子目录和文件的目录。我发现ZipFile有一个方法“ CreateFromDirectory”,它将是理想的选择,除了它需要用于输出文件夹的参数外,该方法也没有返回类型。我如何压缩目录中的所有文件和子文件夹,然后使用ZipFile将它们添加到我的内存流中?

类似的东西

 zip.CreateEntry(ZipFile.CreateFromDirectory(
                            @"C:\morefilestozip\", "",
                            CompressionLevel.Fastest, true));

0 个答案:

没有答案