主要通过System.IO.Compression命名空间下的GZipStream类和DeflateStream类的使用,本实例是通过是哟个GzipStream来实现的,在FileStream的基础上利用Read和Write方法来实现文件的压缩功能。
源代码如下:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Compression;
namespace CompressAndDecompress
{
public partial class Form1 : Form
{
public int Times = 0;
public Form1()
{
InitializeComponent();
}
private void btnSource_Click(object sender, EventArgs e)
{
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
this.txtSource.Text = this.openFileDialog1.FileName;
}
}
private void btnTaget_Click(object sender, EventArgs e)
{
string str = Directory.GetCurrentDirectory();
this.txtTaget.Text = str+"//Compress"+Times.ToString()+".zip";
}
private void btnCompress_Click(object sender, EventArgs e)
{
string sourceFile=this.txtSource.Text.Trim();
string tagetFile=this.txtTaget.Text.Trim();
if(File.Exists(sourceFile)==false)
{
throw new FileNotFoundException();
}
byte[] buf = null;
try
{
using (FileStream fs = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
buf = new byte[fs.Length];
int check = fs.Read(buf, 0, buf.Length);
using (FileStream fss= new FileStream(tagetFile, FileMode.Create, FileAccess.Write))
{
using (GZipStream gs = new GZipStream(fss, CompressionMode.Compress,true))
{
gs.Write(buf, 0, buf.Length);
}
}
}
}
catch (ApplicationException err)
{
MessageBox.Show("压缩文件出错"+err.Message);
}
}
private void btnDecompress_Click(object sender, EventArgs e)
{
string sourceStr=this.txtSource.Text.Trim();
string tagetStr=this.txtTaget.Text.Trim();
if (File.Exists(sourceStr) == false)
{
throw new FileNotFoundException();
}
byte[] buf=null;
try
{
using(FileStream fs=new FileStream(sourceStr,FileMode.Open))
{
using (GZipStream gs = new GZipStream(fs, CompressionMode.Decompress))
{
buf = new byte[5];
int pos = (int)fs.Length - 4;
fs.Position = pos;
fs.Read(buf, 0, 4);
fs.Position = 0;
int check = BitConverter.ToInt32(buf, 0);
byte[] buffer = new byte[check + 100];
int offset = 0;
int total = 0;
while (true)
{
int bytesRead = gs.Read(buffer, offset, 100);
if (bytesRead == 0)
{
break;
}
offset += bytesRead;
total += bytesRead;
}
using (FileStream tagetfs = new FileStream(tagetStr, FileMode.Create))
{
tagetfs.Write(buffer, 0, total);
}
}
}
}
catch (ApplicationException err)
{
MessageBox.Show("解压错误" + err.Message);
}
}
}
}