gpt4 book ai didi

c# - GZIPStream 压缩总是返回 10 个字节

转载 作者:行者123 更新时间:2023-12-04 16:31:03 25 4
gpt4 key购买 nike

我正在尝试压缩我的 UWP 应用程序中的一些文本。我创建此方法是为了以后更容易:

public static byte[] Compress(this string s)
{
var b = Encoding.UTF8.GetBytes(s);
using (MemoryStream ms = new MemoryStream())
using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress))
{
zipStream.Write(b, 0, b.Length);
zipStream.Flush(); //Doesn't seem like Close() is available in UWP, so I changed it to Flush(). Is this the problem?
return ms.ToArray();
}
}

但不幸的是,无论输入文本是什么,它总是返回 10 个字节。是因为我没有在 GZipStream 上使用 .Close() 吗?

最佳答案

您返回字节数据的时间过早。Close() 方法被 Dispose() 方法取代。因此 GZIP 流将仅在您离开 using(GZipStream) {} block 后 处理时写入。

public static byte[] Compress(string s)
{
var b = Encoding.UTF8.GetBytes(s);
var ms = new MemoryStream();
using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress))
{
zipStream.Write(b, 0, b.Length);
zipStream.Flush(); //Doesn't seem like Close() is available in UWP, so I changed it to Flush(). Is this the problem?
}

// we create the data array here once the GZIP stream has been disposed
var data = ms.ToArray();
ms.Dispose();
return data;
}

关于c# - GZIPStream 压缩总是返回 10 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40149163/

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