C# DotNetZip 保存到流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11248096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:07:34  来源:igfitidea点击:

DotNetZip Saving to Stream

c#dotnetzip

提问by user229133

I am using DotNetZip to add a file from a MemoryStreamto a zip file and then to save that zip as a MemoryStreamso that I can email it as an attachment. The code below does not err but the MemoryStreammust not be done right because it is unreadable. When I save the zip to my hard drive everything works perfect, just not when I try to save it to a stream.

我正在使用 DotNetZip 将文件从 a 添加MemoryStream到 zip 文件,然后将该 zip 保存为 a,MemoryStream以便我可以将其作为附件通过电子邮件发送。下面的代码不会出错,但MemoryStream不能正确执行,因为它不可读。当我将 zip 保存到我的硬盘时,一切正常,只是当我尝试将其保存到流时。

using (ZipFile zip = new ZipFile())
{
var memStream = new MemoryStream();
var streamWriter = new StreamWriter(memStream);

streamWriter.WriteLine(stringContent);

streamWriter.Flush();      
memStream.Seek(0, SeekOrigin.Begin);

ZipEntry e = zip.AddEntry("test.txt", memStream);
e.Password = "123456!";
e.Encryption = EncryptionAlgorithm.WinZipAes256;

var ms = new MemoryStream();
ms.Seek(0, SeekOrigin.Begin);

zip.Save(ms);

//ms is what I want to use to send as an attachment in an email                                   
}

采纳答案by Sam I am says Reinstate Monica

I've copied your code, and then saved your final memory steam to disk as data.txt. It was completely unreadable to me, but then I realized that it wasn't a text file, it was a zip file, so i saved it as data.zipand it worked as expected

我已经复制了您的代码,然后将您的最终记忆流以data.txt. 它对我来说完全不可读,但后来我意识到它不是一个文本文件,它是一个 zip 文件,所以我将它另存为data.zip并按预期工作

the method I used to save ms to disk is the following(immediately after your zip.Save(ms);line)

我用来将 ms 保存到磁盘的方法如下(在您的zip.Save(ms);行之后)

            ms.Position = 0;
            byte[] data = ms.ToArray();
            File.WriteAllBytes("data.zip", data);

So, I believe that your memory stream is what It is supposed to be, which is compressed text. It won't be readable until you decompress it.

所以,我相信你的内存流应该是什么,它是压缩文本。在解压之前它是不可读的。

回答by user229133

Ok, I figured out my problem, pretty stupid actually. Thanks for everyone's help!

好吧,我想出了我的问题,实际上很愚蠢。感谢大家的帮助!

ZipEntry e = zip.AddEntry("test.txt", memStream);
e.Password = "123456!";
e.Encryption = EncryptionAlgorithm.WinZipAes256;

//zip.Save("C:\Test\Test.zip");

//Stream outStream;

var ms = new MemoryStream();

zip.Save(ms);

    //--Needed to add the following 2 lines to make it work----
ms.Seek(0, SeekOrigin.Begin);
ms.Flush();