C# 压缩和解压字符串
2022/1/12 11:03:55
本文主要是介绍C# 压缩和解压字符串,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
嗯,就是将比较大的字符串进行压缩,使其占用空间小一点,我一般用在有时候接口间需要传输大量数据的时候(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; }
实现效果:
由简入繁,拿来即用
更多精彩,请关注微信公众号:
这篇关于C# 压缩和解压字符串的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具