字符串的压缩与解压
public static string compress(string aString)
{
if (string.IsNullOrEmpty(aString))
return "";
StringBuilder sb = new StringBuilder();
byte[] byteArray = CompressByte(aString);
foreach (byte item in byteArray)
sb.Append((char)item);
return sb.ToString();
}
public static byte[] CompressByte(string input)
{
byte[] compressed = null;
//SevenZipBase.SetLibraryPath(@"F:\WpfApplication3\WpfApplication3\bin\Debug\SevenZipSharp.dll");
SevenZipCompressor compressor = new SevenZipCompressor();
compressor.CompressionMethod = CompressionMethod.Ppmd;
compressor.CompressionLevel = CompressionLevel.High;
using (MemoryStream msin = GetUTF8MemorySteam(input))
{
using (MemoryStream msout = new MemoryStream())
{
compressor.CompressStream(msin, msout);
msout.Position = 0;
compressed = new byte[msout.Length];
msout.Read(compressed, 0, compressed.Length);
}
}
return compressed;
}
/// <summary>
/// 获取输入字符串的UTF8编码
/// </summary>
/// <param name="input">源字符串</param>
/// <returns>内存数据流</returns>
private static MemoryStream GetUTF8MemorySteam(string input)
{
MemoryStream ms = new MemoryStream();
byte[] bytes = Encoding.Default.GetBytes(input);
ms.Write(bytes, 0, bytes.Length);
return ms;
}
/// <summary>
/// 解压字节数组
/// </summary>
/// <param name="input">源字节数组</param>
/// <returns>解压后字符串</returns>
public static string Decompressbyte(byte[] input)
{
byte[] uncompressedbuffer = null;
using (MemoryStream msin = new MemoryStream())
{
msin.Write(input, 0, input.Length);
uncompressedbuffer = new byte[input.Length];
msin.Position = 0;
using (SevenZipExtractor extractor = new SevenZipExtractor(msin))
{
using (MemoryStream msout = new MemoryStream())
{
extractor.ExtractFile(0, msout);
msout.Position = 0;
uncompressedbuffer = new byte[msout.Length];
msout.Read(uncompressedbuffer, 0, uncompressedbuffer.Length);
}
}
}
return Encoding.Default.GetString(uncompressedbuffer);
}
public static string decompress(string aString)
{
if (string.IsNullOrEmpty(aString))
return "";
int indexBA = 0;
byte[] byteArray = new byte[aString.Length];
foreach (char item in aString.ToCharArray())
byteArray[indexBA++] = (byte)item;
return Decompressbyte(byteArray);
}
下载地址:http://down.51cto.com/data/1333830