C#自定義字符串壓縮和解壓縮的方法
更新時間:2015年04月01日 10:32:24 作者:lele
這篇文章主要介紹了C#自定義字符串壓縮和解壓縮的方法,通過自定義C#字符串操作類實現對字符串的壓縮與解壓的功能,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了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();
希望本文所述對大家的C#程序設計有所幫助。
您可能感興趣的文章:
相關文章
淺談static a[n*m]={0};中static的作用
下面小編就為大家?guī)硪黄獪\談static a[n*m]={0};中static的作用。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03
Unity5.6大規(guī)模地形資源創(chuàng)建方法
這篇文章主要為大家詳細介紹了Unity5.6大規(guī)模地形資源創(chuàng)建方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-02-02

