C#自定義字符串壓縮和解壓縮的方法
更新時(shí)間:2015年04月01日 10:32:24 作者:lele
這篇文章主要介紹了C#自定義字符串壓縮和解壓縮的方法,通過(guò)自定義C#字符串操作類(lèi)實(shí)現(xiàn)對(duì)字符串的壓縮與解壓的功能,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
本文實(shí)例講述了C#自定義字符串壓縮和解壓縮的方法。分享給大家供大家參考。具體如下:
class ZipLib
{
public static string Zip(string value)
{
//Transform string into byte[]
byte[] byteArray = new byte[value.Length];
int indexBA = 0;
foreach (char item in value.ToCharArray())
{
byteArray[indexBA++] = (byte)item;
}
//Prepare for compress
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms,
System.IO.Compression.CompressionMode.Compress);
//Compress
sw.Write(byteArray, 0, byteArray.Length);
//Close, DO NOT FLUSH cause bytes will go missing...
sw.Close();
//Transform byte[] zip data to string
byteArray = ms.ToArray();
System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
foreach (byte item in byteArray)
{
sB.Append((char)item);
}
ms.Close();
sw.Dispose();
ms.Dispose();
return sB.ToString();
}
public static string UnZip(string value)
{
//Transform string into byte[]
byte[] byteArray = new byte[value.Length];
int indexBA = 0;
foreach (char item in value.ToCharArray())
{
byteArray[indexBA++] = (byte)item;
}
//Prepare for decompress
System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray);
System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress);
//Reset variable to collect uncompressed result
byteArray = new byte[byteArray.Length];
//Decompress
int rByte = sr.Read(byteArray, 0, byteArray.Length);
//Transform byte[] unzip data to string
System.Text.StringBuilder sB = new System.Text.StringBuilder(rByte);
//Read the number of bytes GZipStream red and do not a for each bytes in
//resultByteArray;
for (int i = 0; i < rByte; i++)
{
sB.Append((char)byteArray[i]);
}
sr.Close();
ms.Close();
sr.Dispose();
ms.Dispose();
return sB.ToString();
}
}
代碼使用方法:
string str_org="aaaaaaaaaabbbbbbbbbbbbcccccccccdddddddd";
string str_comp = ZipLib.Zip(str_org);
Console.WriteLine("str_comp:" + str_comp);
string str_uncomp = ZipLib.UnZip(str_comp);
Console.WriteLine("str_uncomp:" + str_uncomp);
Console.ReadLine();
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
C# 站點(diǎn)IP訪(fǎng)問(wèn)頻率限制 針對(duì)單個(gè)站點(diǎn)的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇C# 站點(diǎn)IP訪(fǎng)問(wèn)頻率限制 針對(duì)單個(gè)站點(diǎn)的實(shí)現(xiàn)方法。小編覺(jué)的挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-12-12
C#判斷一個(gè)字符串是否是數(shù)字或者含有某個(gè)數(shù)字的方法
這篇文章主要介紹了C#判斷一個(gè)字符串是否是數(shù)字或者含有某個(gè)數(shù)字的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-06-06
Visual C#.Net 網(wǎng)絡(luò)程序開(kāi)發(fā)-Socket篇
Visual C#.Net 網(wǎng)絡(luò)程序開(kāi)發(fā)-Socket篇...2007-03-03
c# 類(lèi)成員的可訪(fǎng)問(wèn)性代碼詳解
在本篇文章里小編給大家整理了關(guān)于c# 類(lèi)成員的可訪(fǎng)問(wèn)性代碼詳解內(nèi)容,有需要的朋友們可以參考下。2019-09-09

