【问题标题】:How to return a .NET Stream of some content but Zip it up along the way如何返回一些内容的 .NET 流,但一路压缩
【发布时间】:2023-03-24 08:39:01
【问题描述】:

我有一个很大的XDocument。我正在尝试将其流式传输到某个地方:

public StreamResponse(Func<System.IO.Stream> source)

为此,我已经完成了:

Stream stream = new MemoryStream();  // Create a stream
xmlDocument.Save(stream);      // Save XDocument into the stream
stream.Position = 0;

return new StreamResponse(() => stream);

而且效果很好。

现在,是否可以更改此设置,以便我流出内存流的 ZIP。

像这样 => XDocument => MemoryStream => ZIP Stream => stream-end-point ?

【问题讨论】:

    标签: c# .net stream


    【解决方案1】:
    Stream stream = new MemoryStream();  // Create a stream
    Stream compressed = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionLevel.Optimal);
    xmlDocument.Save(compressed);      // Save XDocument into the stream
    compressed.Position = 0;
    
    return new StreamResponse(() => stream);
    

    文档:GZipStream

    【讨论】:

      【解决方案2】:

      是的,使用DotNetZip 将您的 Memory Stream 传递给 save 方法。像这样的:

           using (ZipFile zip = new ZipFile())
           {
               // add this map file into the "images" directory in the zip archive
               zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
               // add the report into a different directory in the archive
               zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
               zip.AddFile("ReadMe.txt");
               zip.Save(myStream);
           }
      

      【讨论】:

        【解决方案3】:

        GZipStream 来救你了!

        来自 MSDN:

        GZipStream 类

        提供用于压缩和解压缩流的方法和属性。

        https://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream%28v=vs.110%29.aspx

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-22
          • 2017-01-20
          • 1970-01-01
          • 2022-11-30
          • 2012-03-20
          • 2016-10-26
          相关资源
          最近更新 更多