using System;
using System.Collections.Generic;
using System.Text;using System.IO;
using System.IO.Compression;
//使用压缩类 class Test
{staticvoid SaveCompressedFile(string filename, string data) 
{//创建一个 FileStream 对象 
FileStream fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write); 
//创建一个 GZipStream 对象,Compress 表示压缩基础流。 
GZipStream compressionStream = new GZipStream(fileStream, CompressionMode.Compress); 
//实现一个 write,使其以一种特定的编码向流中写入字符。
 StreamWriter writer = new StreamWriter(compressionStream); 
writer.Write(data);
 writer.Close();
 }
staticstring LoadCompressedFile(string filename) 
{//创建一个 FileStream 对象
 FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read); 
//创建一个 GZipStream 对象,Decompress 表示解压缩基础流。
 GZipStream compressionStream = new GZipStream(fileStream, CompressionMode.Decompress); 
//实现从字符串进行读取 
StreamReader reader = new StreamReader(compressionStream);
string data = reader.ReadToEnd(); reader.Close();
return data; }
 publicstaticvoid Main(string[] args) 
{
try 
{
//定义文件路径
string filename = @"c:/compressedFile.txt";
 Console.WriteLine("Enter a string to compress (will be repeated 10 times):");
//再控制台上输入文字
string sourceString = Console.ReadLine(); 
StringBuilder sourceStringMultiplier = new StringBuilder(sourceString.Length * 100);
for (int i = 0; i < 100; i++) 
{ sourceStringMultiplier.Append(sourceString); } 
sourceString = sourceStringMultiplier.ToString();
 Console.WriteLine("Source data is {0} bytes long.", sourceString.Length); 
SaveCompressedFile(filename, sourceString); 
Console.WriteLine("/nData saved to {0}.", filename);
 FileInfo compressedFileData = new FileInfo(filename); 
Console.WriteLine("Compressed file is {0} bytes long.", compressedFileData.Length); 
string recoveredString = LoadCompressedFile(filename); 
recoveredString = recoveredString.Substring(0, recoveredString.Length / 100); 
Console.WriteLine("/nRecovered data: {0}", recoveredString); 
Console.ReadKey(); 
}
catch (IOException ex) 
{ Console.WriteLine("An IO exception has been thrown!");
 Console.WriteLine(ex.ToString()); Console.ReadKey(); } }}
posted on 2012-03-06 09:58  瓦里奥  阅读(4619)  评论(0编辑  收藏  举报