嗯,就是將比較大的字符串進(jìn)行壓縮,使其占用空間小一點,一般用在有時候接口間需要傳輸大量數(shù)據(jù)的時候(json數(shù)據(jù)較大或者含有base64),縮小體積以加快傳輸小效率。
實現(xiàn)功能:
開發(fā)環(huán)境:
開發(fā)工具:Visual Studio 2013
.NET Framework版本:4.5
實現(xiàn)代碼:
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;
}
實現(xiàn)效果:
該文章在 2023/2/27 10:52:12 編輯過