如何在内存中创建zip文件,从文件字节开始
本文关键字:文件 字节 开始 zip 创建 内存 | 更新日期: 2023-09-27 18:02:05
我尝试用c#在内存中创建一个zip文件,但结果是一个zip文件里面有损坏的文件。所有要压缩的文件都在数据库中。我存储字节。文件为PDF格式。我的代码如下
//[extract bytes and file name for every file]
using (var zipArchiveMemoryStream = new MemoryStream())
{
using (var zipArchive = new ZipArchive(zipArchiveMemoryStream,
ZipArchiveMode.Create, true))
{
foreach (var file in fileData)
{
var zipEntry = zipArchive.CreateEntry(file.FileName);
using (var entryStream = zipEntry.Open())
{
using (var tmpMemory = new MemoryStream(file.Bytes))
{
tmpMemory.CopyTo(entryStream);
};
}
}
}
zipArchiveMemoryStream.Position = 0;
result = zipArchiveMemoryStream.GetBuffer();
//[download zip file]
提前感谢您的支持
解:问题是我使用GetBuffer();而不是ToArray ();
using (var zipArchiveMemoryStream = new MemoryStream())
{
using (var zipArchive = new ZipArchive(zipArchiveMemoryStream, ZipArchiveMode.Create, true))
{
foreach (var file in fileData)
{
var zipEntry = zipArchive.CreateEntry(file.FileName);
using (var entryStream = zipEntry.Open())
{
using (var tmpMemory = new MemoryStream(file.Bytes))
{
tmpMemory.CopyTo(entryStream);
};
}
}
}
zipArchiveMemoryStream.Seek(0, SeekOrigin.Begin);
result = zipArchiveMemoryStream.ToArray();
}
return result;
试着看看这个:使用System.IO.Compression在内存中创建ZIP存档。解决方案如下:
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
var demoFile = archive.CreateEntry("foo.txt");
using (var entryStream = demoFile.Open())
using (var streamWriter = new StreamWriter(entryStream))
{
streamWriter.Write("Bar!");
}
}
using (var fileStream = new FileStream(@"C:'Temp'test.zip", FileMode.Create))
{
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(fileStream);
}
}
它解释了如何在内存中创建zip存档,并包含了另一篇有用文章的链接,该文章解释了如何使用leaveOpen参数来防止流的关闭:
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);
}
}
我希望这是有帮助的!
编辑
用zipArchiveMemoryStream.ToArray()
代替zipArchiveMemoryStream.GetBuffer()
对我来说是这样的:
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
var file = archive.CreateEntry("file.json");
using var entryStream = file.Open();
using var streamWriter = new StreamWriter(entryStream);
streamWriter.WriteLine(someJsonLine);
}
}