gpt4 book ai didi

c# - 打包(.zip)一个字节数组文件.net core

转载 作者:行者123 更新时间:2023-12-01 22:55:19 33 4
gpt4 key购买 nike

我试着按照这个 SO: Create zip file from byte[]作为一个虚拟项目,它看起来像这样:

using System.IO.Compression;
using System.IO;
using System.Net.Http;
using System;

namespace TestApp
{
internal class Program
{
static void Main(string[] args)
{
using var compressedFileStream = new MemoryStream();
using var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create);

//Create a zip entry for each attachment
var zipEntry = zipArchive.CreateEntry("test.txt");
var file = File.ReadAllBytes("test.txt");

//Get the stream of the attachment
using var originalFileStream = new MemoryStream(file);
using var zipEntryStream = zipEntry.Open();
//Copy the attachment stream to the zip entry stream
originalFileStream.CopyTo(zipEntryStream);

var toarraybaby = compressedFileStream.ToArray();

File.WriteAllBytes("hehe.zip", toarraybaby);
}
}
}

我得到一个 .zip 文件作为输出,该文件有一个大小。但是当试图打开文件时,我发现它已损坏。我错过了什么?

最佳答案

该代码的具体问题在于 C# 8 风格的 using 声明将 at 置于当前作用域的末尾。那太晚了。必须处理 zip 存档以确保将所有必要的数据写入其输出流,但在执行此操作时,Main 已结束。

有多种方法可以确保它尽早处理,例如:

using var compressedFileStream = new MemoryStream();
// using an old-style using statement here to ensure the zip archive gets disposed early enough
using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create))
{
//Create a zip entry for each attachment
var zipEntry = zipArchive.CreateEntry("test.txt");
var file = File.ReadAllBytes("test.txt");

//Get the stream of the attachment
using var originalFileStream = new MemoryStream(file);
using var zipEntryStream = zipEntry.Open();
//Copy the attachment stream to the zip entry stream
originalFileStream.CopyTo(zipEntryStream);

}
var toarraybaby = compressedFileStream.ToArray();

File.WriteAllBytes("hehe.zip", toarraybaby);

关于c# - 打包(.zip)一个字节数组文件.net core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73398724/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com