GZipStream压缩和解压缩方法

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(); } }}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值