嗯,就是将比较大的字符串进行压缩,使其占用空间小一点,我一般用在有时候接口间需要传输大量数据的时候(json数据较大或者含有base64),缩小体积以加快传输小效率。
实现功能:
压缩和解压字符串
开发环境:
开发工具:VisualStudio2013
.NETFramework版本:4.5
实现代码:
stringfileData="",compress="";privatevoidbtnPath_Click(objectsender,EventArgse){OpenFileDialogofd=newOpenFileDialog();if(ofd.ShowDialog()==DialogResult.OK){textBox1.Text=ofd.FileName;FileInfofi=newFileInfo(ofd.FileName);GetSize(fi.Length,lbFile);fileData=File.ReadAllText(ofd.FileName);}}privatevoidbtnCompress_Click(objectsender,EventArgse){compress=Compress(fileData);GetSize(Encoding.Default.GetBytes(compress).Length,lbCompress);MessageBox.Show("成功");}privatevoidbtnDecompress_Click(objectsender,EventArgse){richTextBox1.Text=Decompress(compress);MessageBox.Show("成功");}//压缩字符串publicstringCompress(stringvalue){try{stringdata="";byte[]byteArray=Encoding.Default.GetBytes(value);using(MemoryStreamms=newMemoryStream()){using(GZipStreamsw=newGZipStream(ms,CompressionMode.Compress)){sw.Write(byteArray,0,byteArray.Length);GetSize(ms.Length,lbCompress);}data=Convert.ToBase64String(ms.ToArray());}returndata;}catch(Exceptionex){throwex;}}//解压缩字符串publicstringDecompress(stringvalue){try{stringdata="";byte[]bytes=Convert.FromBase64String(value);using(MemoryStreammsReader=newMemoryStream()){using(MemoryStreamms=newMemoryStream(bytes)){using(GZipStreamzip=newGZipStream(ms,CompressionMode.Decompress)){byte[]buffer=newbyte[1024];intreadLen=0;while((readLen=zip.Read(buffer,0,buffer.Length))>0){msReader.Write(buffer,0,readLen);}}}data=Encoding.Default.GetString(msReader.ToArray());}returndata;}catch(Exceptionex){throwex;}}//获取大小privatevoidGetSize(longsize,Controlcontrol){stringsizeStr="";if(size<1024)sizeStr=size.ToString("F2")+"Byte";elseif(size>=1024&&size<1048576)sizeStr=(size/1024).ToString("F2")+"K";elseif(size>=1048576&&size<1073741824)sizeStr=(size/1024/1024).ToString("F2")+"M";elseif(size>=1073741824)sizeStr=(size/1024/1024/1024).ToString("F2")+"G";control.Text=sizeStr;}
实现效果: