2013-05-17 123 views
0

我知道有system.io.compression.gzipstream,但它接受流作爲參數。c#中的壓縮和解壓縮字符串

我找了接受字符串

如方法。

string compress(string stringtocompress,compressionlevel level); 
string decompress(string stringtodecompress); 
+0

可能重複http://stackoverflow.com/questions/7343465/compression-decompression-string-with -c-尖銳) – alxx

回答

13

你應該試試這個:

using System; 
using System.IO; 
using System.IO.Compression; 
using System.Text; 

... 

public static string Compress(string s) 
{ 
    var bytes = Encoding.Unicode.GetBytes(s); 
    using (var msi = new MemoryStream(bytes)) 
    using (var mso = new MemoryStream()) 
    { 
     using (var gs = new GZipStream(mso, CompressionMode.Compress)) 
     { 
      msi.CopyTo(gs); 
     } 
     return Convert.ToBase64String(mso.ToArray()); 
    } 
} 

public static string Decompress(string s) 
{ 
    var bytes = Convert.FromBase64String(s); 
    using (var msi = new MemoryStream(bytes)) 
    using (var mso = new MemoryStream()) 
    { 
     using (var gs = new GZipStream(msi, CompressionMode.Decompress)) 
     { 
      gs.CopyTo(mso); 
     } 
     return Encoding.Unicode.GetString(mso.ToArray()); 
    } 
} 
[用C#壓縮/解壓縮串(的