C# 压缩和解压字符串
|
admin
2023年2月27日 10:52
本文热度 470
|
嗯,就是将比较大的字符串进行压缩,使其占用空间小一点,一般用在有时候接口间需要传输大量数据的时候(json数据较大或者含有base64),缩小体积以加快传输小效率。
实现功能:
开发环境:
开发工具:Visual Studio 2013
.NET Framework版本:4.5
实现代码:
string fileData = "", compress = "";
private void btnPath_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
FileInfo fi = new FileInfo(ofd.FileName);
GetSize(fi.Length, lbFile);
fileData = File.ReadAllText(ofd.FileName);
}
}
private void btnCompress_Click(object sender, EventArgs e)
{
compress = Compress(fileData);
GetSize(Encoding.Default.GetBytes(compress).Length, lbCompress);
MessageBox.Show("成功");
}
private void btnDecompress_Click(object sender, EventArgs e)
{
richTextBox1.Text = Decompress(compress);
MessageBox.Show("成功");
}
public string Compress(string value)
{
try
{
string data = "";
byte[] byteArray = Encoding.Default.GetBytes(value);
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream sw = new GZipStream(ms, CompressionMode.Compress))
{
sw.Write(byteArray, 0, byteArray.Length);
GetSize(ms.Length, lbCompress);
}
data = Convert.ToBase64String(ms.ToArray());
}
return data;
}
catch (Exception ex)
{
throw ex;
}
}
public string Decompress(string value)
{
try
{
string data = "";
byte[] bytes = Convert.fromBase64String(value);
using (MemoryStream msReader = new MemoryStream())
{
using (MemoryStream ms = new MemoryStream(bytes))
{
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
byte[] buffer = new byte[1024];
int readLen = 0;
while ((readLen = zip.Read(buffer, 0, buffer.Length)) > 0)
{
msReader.Write(buffer, 0, readLen);
}
}
}
data = Encoding.Default.GetString(msReader.ToArray());
}
return data;
}
catch (Exception ex)
{
throw ex;
}
}
private void GetSize(long size, Control control)
{
string sizeStr = "";
if (size < 1024)
sizeStr = size.ToString("F2") + " Byte";
else if (size >= 1024 && size < 1048576)
sizeStr = (size / 1024).ToString("F2") + " K";
else if (size >= 1048576 && size < 1073741824)
sizeStr = (size / 1024 / 1024).ToString("F2") + " M";
else if (size >= 1073741824)
sizeStr = (size / 1024 / 1024 / 1024).ToString("F2") + " G";
control.Text = sizeStr;
}
实现效果:
该文章在 2023/2/27 10:52:12 编辑过