gpt4 book ai didi

C# - 压缩字节[]

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:09 25 4
gpt4 key购买 nike

我收到一个 zip 文件 base64 字符串,转换为 byte[],在内存中打开,修改内容,然后再次“压缩”新的 byte[] 为 base64 字符串。

我的问题是,我不知道如何将新的 byte[] 压缩为 zip 格式。

public string ModifyZipContent(string base64) {
ZipPackage zipPackage = null;
MemoryStream memoryStream = null;

long lenght;

byte[] data = Convert.FromBase64String(base64);
byte[] buffer;
byte[] newData;

int arrayOffset = 0;

memoryStream = new MemoryStream();
memoryStream.Write(data, 0, data.Length);

zipPackage = (ZipPackage)Package.Open(memoryStream, FileMode.Open);

PackagePartCollection zipParts = zipPackage.GetParts();

// this is awful
foreach(ZipPackagePart zipPart in zipParts) {
using(Stream stream = zipPart.GetStream()) {
arrayOffset += (int)stream.Length;
}
}

newData = new byte[arrayOffset];
// end

arrayOffset = 0;
foreach(ZipPackagePart zipPart in zipParts) {
using(Stream stream = zipPart.GetStream()) {
lenght = stream.Length;
buffer = new byte[lenght];

stream.Read(buffer, 0, (int)lenght);

Buffer.BlockCopy(buffer, 0, newData, arrayOffset, buffer.Length);
arrayOffset += buffer.Length;
}
}

return Convert.ToBase64String(newData);
}

最佳答案

我还没有完全测试过这个,但是按照这些思路应该可以工作......

// Requires System.IO.Compression using statement.

byte[] bytes = new byte[256]; // Your byte[] would be here instead of this empty one.
using (var zipFile = ZipFile.Open("C:/ZipFile.zip", ZipArchiveMode.Update))
{
var entry = zipFile.CreateEntry("YourEntryPathHere");
using (var stream = entry.Open())
{
stream.Write(bytes, 0, bytes.Length);
}
}

关于C# - 压缩字节[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36453604/

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