文件压缩和解压 FileStream GZipStream

时间:2022-03-16 11:38:37
  using (FileStream reader=new FileStream (@"c:\1.txt",FileMode.Open,FileAccess.Read))
{
using (FileStream writer=new FileStream (@"c:\4.zp",FileMode.OpenOrCreate,FileAccess.Write))
{
//压缩写的流
using (GZipStream zip=new GZipStream (writer,CompressionMode.Compress))
{
byte[] buffer = new byte[];
int r = ;
while ((r=reader.Read(buffer,,buffer.Length))>)
{
//压缩写入
zip.Write(buffer,,r); }
}
}
}
Console.WriteLine("/压缩完成"); using (FileStream reader = new FileStream(@"c:\4.zp", FileMode.OpenOrCreate, FileAccess.Read))
{
using (FileStream writer = new FileStream(@"c:\5.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
byte[] buffer = new byte[];
//解压读的流 因读的是压缩文件,reader读出的是压缩后的流
using (GZipStream zip = new GZipStream(reader, CompressionMode.Decompress))
{
int r=; while ((r = zip.Read(buffer, , buffer.Length)) > )
{
//正常的流写入
writer.Write(buffer, , r);
}
} }
}

这种压缩只能实现单个文件的压缩和解压,多个文件的暂时不能使用