gpt4 book ai didi

asp.net - c#中压缩和解压字符串

转载 作者:行者123 更新时间:2023-12-01 15:34:20 25 4
gpt4 key购买 nike

我知道有 system.io.compression.gzipstream 但它接受流作为参数。

我正在寻找一种接受字符串的方法

例如。

string compress(string stringtocompress,compressionlevel level);
string decompress(string stringtodecompress);

最佳答案

你应该试试这个:

using System;
using System.IO;
using System.IO.Compression;
using System.Text;

...

public static string Compress(string s)
{
var bytes = Encoding.Unicode.GetBytes(s);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
msi.CopyTo(gs);
}
return Convert.ToBase64String(mso.ToArray());
}
}

public static string Decompress(string s)
{
var bytes = Convert.FromBase64String(s);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
{
gs.CopyTo(mso);
}
return Encoding.Unicode.GetString(mso.ToArray());
}
}

关于asp.net - c#中压缩和解压字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16606552/

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