Gzipstream 解压问题
2012-03-02 13:14 小sa 阅读(434) 评论(0) 编辑 收藏 举报Gzipstream 解压问题
static void Main(string[] args) { string path = @"C:\fg.txt"; //压缩前 string pathdes=@"C:\fg1.txt"; //压缩后 string depath = @"C:\fg2.txt"; //还原为 GzipFile(path, pathdes); DeGzipFile(pathdes,depath ); Console.Read(); } /// <summary> /// 压缩文件 /// </summary> /// <param name="soursPath"></param> /// <param name="desPath"></param> static void GzipFile(string soursPath, string desPath) { //File.ReadAllText(Path,Encoding.Default) byte[] compressed = Compress(File.ReadAllBytes(soursPath)); File.WriteAllBytes(desPath, compressed); } /// <summary> /// 解压文件 /// </summary> /// <param name="soursPath"></param> /// <param name="desPath"></param> static void DeGzipFile(string soursPath, string desPath) { byte[] compressed = Decompress(File.ReadAllBytes(soursPath)); File.WriteAllBytes(desPath, compressed); } /// <summary> /// 压缩流 /// </summary> /// <param name="data">byte[] 输入流</param> /// <returns>输出流byte[]</returns> public static byte[] Compress(byte[] data) { byte[] result; Console.WriteLine("初始大小:\t{0} bytes", data.Length); using (MemoryStream baseStream = new MemoryStream()) { using (GZipStream stream = new GZipStream(baseStream, CompressionMode.Compress, true)) { stream.Write(data, 0, data.Length); } result = baseStream.ToArray(); // only safe to read after deflate closed } Console.WriteLine("压缩后大小:\t{0} bytes", result.Length); return result; } /// <summary> /// 将流解压缩 /// </summary> /// <param name="data">byte[] 输入流</param> /// <returns>输出流byte[]</returns> public static byte[] Decompress(byte[] data) { byte[] result; Console.WriteLine("解压前大小:\t{0} bytes", data.Length); using (MemoryStream mStream = new MemoryStream(data)) { using (GZipStream gStream = new GZipStream(mStream, CompressionMode.Decompress)) { StreamReader streamR = new StreamReader(gStream, Encoding.Default);//此处Encoding 选择默认 string outs = streamR.ReadToEnd();//也可以直接返回字符串 result = Encoding.Default.GetBytes(outs); } } Console.WriteLine("解压后大小:\t{0} bytes", result.Length); return result; }