C#對字符串進行壓縮和解壓縮的算法代碼
C#對字符串進行壓縮和解壓縮的算法代碼,字符串通過base64編碼后傳輸
public class Compression
{
/// <summary>
/// 對字符串進行壓縮
/// </summary>
/// <param name="str">待壓縮的字符串</param>
/// <returns>壓縮后的字符串</returns>
public static string CompressString(string str)
{
string compressString = "";
byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
byte[] compressAfterByte=Compress(compressBeforeByte);
//compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
compressString = Convert.ToBase64String(compressAfterByte);
return compressString;
}
/// <summary>
/// 對字符串進行解壓縮
/// </summary>
/// <param name="str">待解壓縮的字符串</param>
/// <returns>解壓縮后的字符串</returns>
public static string DecompressString(string str)
{
string compressString = "";
//byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
byte[] compressBeforeByte = Convert.FromBase64String(str);
byte[] compressAfterByte = Decompress(compressBeforeByte);
compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
return compressString;
}
/// <summary>
/// 對文件進行壓縮
/// </summary>
/// <param name="sourceFile">待壓縮的文件名</param>
/// <param name="destinationFile">壓縮后的文件名</param>
public static void CompressFile(string sourceFile, string destinationFile)
{
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// 對文件進行解壓縮
/// </summary>
/// <param name="sourceFile">待解壓縮的文件名</param>
/// <param name="destinationFile">解壓縮后的文件名</param>
/// <returns></returns>
public static void DecompressFile(string sourceFile, string destinationFile)
{
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// 對byte數組進行壓縮
/// </summary>
/// <param name="data">待壓縮的byte數組</param>
/// <returns>壓縮后的byte數組</returns>
public static byte[] Compress(byte[] data)
{
try
{
MemoryStream ms = new MemoryStream();
GZipStream zip = new GZipStream(ms, CompressionMode.Compress,true);
zip.Write(data, 0, data.Length);
zip.Close();
byte[] buffer = new byte[ms.Length];
ms.Position=0;
ms.Read(buffer, 0, buffer.Length);
ms.Close();
return buffer;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
public static byte[] Decompress(byte[] data)
{
try
{
MemoryStream ms = new MemoryStream(data);
GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true);
MemoryStream msreader = new MemoryStream();
byte[] buffer = new byte[0x1000];
while (true)
{
int reader = zip.Read(buffer, 0, buffer.Length);
if (reader <= 0)
{
break;
}
msreader.Write(buffer, 0, reader);
}
zip.Close();
ms.Close();
msreader.Position = 0;
buffer = msreader.ToArray();
msreader.Close();
return buffer;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}</pre>
本文由用戶 b5cw 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!