问题描述
我想创建一个从code新的ZIP包与一个条目和ZIP包保存到一个文件中。我试图用 System.IO.Com pression.ZipArchive 类achive这一点。我用下面的code创建ZIP包:
I am trying to create a new ZIP package from code with one entry and save the ZIP package to a file. I am trying to achive this with the System.IO.Compression.ZipArchive class. I am creating the ZIP package with the following code:
using (MemoryStream zipStream = new MemoryStream())
{
using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create))
{
var entry = zip.CreateEntry("test.txt");
using (StreamWriter sw = new StreamWriter(entry.Open()))
{
sw.WriteLine(
"Etiam eros nunc, hendrerit nec malesuada vitae, pretium at ligula.");
}
然后,我的ZIP保存到文件中或者在WinRT的:
Then I save the ZIP to a file either in WinRT:
var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("test.zip", CreationCollisionOption.ReplaceExisting);
zipStream.Position = 0;
using (Stream s = await file.OpenStreamForWriteAsync())
{
zipStream.CopyTo(s);
}
还是在正常的.NET 4.5:
Or in normal .NET 4.5:
using (FileStream fs = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
{
zipStream.Position = 0;
zipStream.CopyTo(fs);
}
不过,我无法打开生成的文件无论是在Windows资源管理器时,WinRAR等(我检查了生成的文件的大小相匹配的zipStream的长度,所以流本身是正确保存到文件中。 )
我是不是做错了什么或有与ZipArchive类的问题?
However, I can't open the produced files neither in Windows Explorer, WinRAR, etc. (I checked that the size of the produced file matches the Length of the zipStream, so the stream itself was saved to the file correctly.)
Am I doing something wrong or is there a problem with the ZipArchive class?
推荐答案
我发现 - 在回顾展,很明显。该ZipArchive必须的设置,以使其写入其内容,其底层流。所以我不得不流保存到ZipArchive的使用块结束后文件。
而且,重要的是将 leaveOpen 其构造为true的参数,使之不关闭底层流。因此,这里是整个工作的解决方案:
I found the - in retrospective, obvious - error in my code. The ZipArchive has to be disposed to make it write its content to its underlying stream. So I had to save the stream to a file after the end of the using block of the ZipArchive.
And it was important to set the leaveOpen argument of its constructor to true, to make it not close the underlying stream. So here is the complete working solution:
using (MemoryStream zipStream = new MemoryStream())
{
using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
var entry = zip.CreateEntry("test.txt");
using (StreamWriter sw = new StreamWriter(entry.Open()))
{
sw.WriteLine(
"Etiam eros nunc, hendrerit nec malesuada vitae, pretium at ligula.");
}
}
var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(
"test.zip",
CreationCollisionOption.ReplaceExisting);
zipStream.Position = 0;
using (Stream s = await file.OpenStreamForWriteAsync())
{
zipStream.CopyTo(s);
}
}
这篇关于ZipArchive创建无效的ZIP文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!