C# 似乎无法正确地将图像添加到 ziarchive

C# can't seem to correctly add images to ziparchive

我正在尝试将一堆文件添加到 c# 中的 zip 文件中,但它似乎无法正常工作。

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 文件并将其保存到具有预期文件大小的磁盘中。

但是当我尝试在 windows 照片查看器中打开它们时,它们似乎已损坏。

感谢任何帮助。

几乎花了 3 个小时才弄清楚问题出在哪里。如果您查看原始图像和提取图像的大小,会有微小的差异。

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())
                {// to keep it as image better to have it as bytes
                    var bytes = stream.ToArray();
                    entryStream.Write(bytes, 0, bytes.Length); 
                }
            }
        }
    }

    using (var fileStream = new FileStream(@"test.zip", FileMode.Create))
    {
        memoryStream.Seek(0, SeekOrigin.Begin);
        memoryStream.CopyTo(fileStream);
    }
}

我试过了,效果很好!