C#似乎无法正确添加图像到ziparchive [英] C# can't seem to correctly add images to ziparchive
本文介绍了C#似乎无法正确添加图像到ziparchive的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将一堆文件添加到c#中的zip文件中,但它似乎无法正常工作。
I'm trying to add a bunch of files to a zipfile in c# but it doesn't seem to work properly.
using (var memoryStream = new MemoryStream())
{
using (var zip = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
for (int i = 0; i < kaart_data.GetLength(0); i++)
{
Image img = array[i];
var file = zip.CreateEntry(i + ".bmp");
using (var stream = new MemoryStream())
{
img.Save(stream, ImageFormat.Bmp);
using (var entryStream = file.Open())
{
stream.CopyTo(entryStream);
}
}
}
}
//saves the archive to disk
using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
{
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(fileStream);
}
}
事情是它确实创建并保存了zip文件使用预期的文件大小进入磁盘。
The thing is it does create and save the zip file into disk with the expected file size.
但是当我尝试在Windows照片查看器中打开它们时,它们似乎已损坏。
But when I try to open them in windows photo viewer they seem to be corrupted.
任何帮助都表示赞赏。
推荐答案
几乎花了3个小时来弄清问题是什么。如果你看一下原始图像的大小并提取一个,就会有一点不同。
It almost took 3 hrs to figure out what's the issue. If u look at the the size of original image and extracted one, there's a tiny difference.
using (var memoryStream = new MemoryStream())
{
using (var zip = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
for (var i = 0; i < images.Length; i++)
{
var img = images[i];
var file = zip.CreateEntry(i + ".bmp");
using (var stream = new MemoryStream())
{
img.Save(stream, ImageFormat.Bmp);
using (var entryStream = file.Open())
{
var bytes = stream.ToArray(); -- to keep it as image better to have it as bytes
entryStream.Write(bytes, 0, bytes.Length);
}
}
}
}
using (var fileStream = new FileStream(@"test.zip", FileMode.Create))
{
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(fileStream);
}
}
我试过它就像魅力一样!
I've tried it it works like a charm!
这篇关于C#似乎无法正确添加图像到ziparchive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文