C# Ionic Zip:从字节创建 Zip 文件[]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9855633/
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
Ionic Zip : Zip file creation from byte[]
提问by Cannon
Ionic zip allows me to add existing file to zip object and create a zip file. But considering that I am reading those byte[] from created zip file and sending over server, I need to again create zip file from that byte[] to store zip on server. How do I achieve this ?
Ionic zip 允许我将现有文件添加到 zip 对象并创建一个 zip 文件。但是考虑到我正在从创建的 zip 文件中读取这些字节 [] 并通过服务器发送,我需要再次从该字节 [] 创建 zip 文件以将 zip 存储在服务器上。我如何实现这一目标?
I am using C#.
我正在使用 C#。
采纳答案by hangy
If I understand your question correctly, you get your byte[]data array over the network and want to save that data in a zip file? You can create a new ZipEntryfrom a MemoryStreamwhich you create from the byte[]you got (as shown in the docs):
如果我正确理解您的问题,您是否byte[]通过网络获取数据数组并希望将该数据保存在 zip 文件中?您可以从您获得的ZipEntrya创建一个新的(如文档中所示):MemoryStreambyte[]
byte[] data = MethodThatReceivesYourDataOverTheNet();
using (MemoryStream stream = new MemoryStream(data))
{
using (ZipFile zip = new ZipFile())
{
zip.AddEntry("name_of_the_file_in_the_arhive.bin", "base", stream);
zip.Save("example.zip");
}
}
回答by Jon Skeet
It's not really clear from your question what you're doing - but if you're just trying to avoid saving to disk and then reloading to get the data, just save to a MemoryStream:
从您的问题中并不清楚您在做什么 - 但如果您只是想避免保存到磁盘然后重新加载以获取数据,只需保存到MemoryStream:
byte[] data;
using (MemoryStream ms = new MemoryStream())
{
zipFile.Save(ms);
data = ms.ToArray();
}
// Do whatever with data.
Alternatively, use MemoryStream.GetBuffer()to avoid making another copy:
或者,使用MemoryStream.GetBuffer()以避免制作另一个副本:
byte[] buffer;
int length;
using (MemoryStream ms = new MemoryStream())
{
zipFile.Save(ms);
buffer = ms.ToArray();
length = ms.Length;
}
// Now use buffer, but only up to "length"...

