您的位置:首页 > 编程语言 > C#

C#压缩与解压文件源码

2008-03-25 17:57 471 查看
//获得压缩的文件夹
//压缩文件夹的名字
string name = file + ".rar";
//压缩文件的流对象
// MessageBox.Show(name);
ZipOutputStream output = new ZipOutputStream(File.Create(name));
output.SetLevel(6);
string[] dir = Directory.GetFiles(file);
//存放文件数据
Crc32 crc = new Crc32();
foreach (string myFile in dir)
{
FileStream fs = new FileStream(myFile, FileMode.Open, FileAccess.Read);
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, bt.Length);
//存储要压缩的文件
ZipEntry entry = new ZipEntry(myFile);
entry.Size = fs.Length;
entry.DateTime = DateTime.Now;
fs.Close();
crc.Reset(); //清除crc内容
crc.Update(bt); //更新文件内容到crc中
entry.Crc = crc.Value; //将文件内容放到压缩文件中
output.PutNextEntry(entry);
//将数据写入压缩流中
output.Write(bt, 0, bt.Length);
}
output.Close();
MessageBox.Show("压缩成功");

解压文件

string file = this.txtUZip.Text;
//读压缩文件内容流
ZipInputStream input = new ZipInputStream(File.OpenRead(file));
ZipEntry entry = input.GetNextEntry();
//要存放的路径
string dir = this.txtPath.Text;
while (entry != null)
{
string filename = entry.Name;
//读压缩文件内容
int size = 2048;
byte[] bt = new byte[size];
FileStream inpuFs = File.Create(dir+filename.Substring(filename.LastIndexOf("//")));
while (true)
{
size = input.Read(bt, 0, bt.Length);
if (size > 0)
{
inpuFs.Write(bt, 0, size);
}
else
{
inpuFs.Close();
break;
}
}
entry = input.GetNextEntry();
}
input.Close();

源码下载

http://download.csdn.net/source/394595
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: