这个功能完全依靠一个第三方的类,ICSharpCode.SharpZipLib.dll,只是在网上搜了大半天,都没有关于这个类的详细解释,搜索的demo也是各种错误,感觉作者完全没有跑过,就那么贸贸然的贴出来了。当然这个功能的实现也是基于前人的Demo,感恩!
我创建的是个Windows窗体应用程序取名为ZipDemo。
1. 拖了2个文本框,4个按钮

2. 添加引用ICSharpCode.SharpZipLib.dll
3. 压缩的代码
//选择文件夹 private void btnOpen_Click(object sender, EventArgs e) { FolderBrowserDialog dialog = new FolderBrowserDialog();//打开文件夹 if (dialog.ShowDialog() != DialogResult.OK) { return; } txtPath.Text = dialog.SelectedPath; } //开始压缩 private void btnZip3_Click(object sender, EventArgs e) { ZipOutputStream zipStream = new ZipOutputStream(File.Create(Path.GetFileName(txtPath.Text) + ".zip"));//压缩到Debug中 AddZip3(txtPath.Text, ref zipStream); zipStream.Finish(); zipStream.Close(); MessageBox.Show("压缩完成"); } //递归压缩 void AddZip3(string path, ref ZipOutputStream zipStream) { //如果是文件,则压缩 if (File.Exists(path)) { zipStream.SetLevel(9); //压缩等级 FileStream f = File.OpenRead(path); byte[] b = new byte[f.Length]; f.Read(b, 0, b.Length); //将文件流加入缓冲字节中 string filePath = path.Replace(txtPath.Text, string.Empty).Remove(0, 1);//取相对路径,并且去掉前面的/,否则压缩的文件和文件夹名称前都会加个/ ZipEntry z = new ZipEntry(filePath);//如果是文件夹下的文件,会自动创建文件夹 zipStream.PutNextEntry(z); //为压缩文件流提供一个容器 zipStream.Write(b, 0, b.Length); //写入字节 f.Close(); } //如果是文件夹,则循环里面的文件和文件夹 if (Directory.Exists(path)) { DirectoryInfo di = new DirectoryInfo(path); foreach (var item in di.GetDirectories()) { AddZip3(item.FullName, ref zipStream); } foreach (var item in di.GetFiles()) { AddZip3(item.FullName, ref zipStream); } } }
4. 解压缩的代码
//选择文件 private void btnOpenFile_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); if (ofd.ShowDialog() != DialogResult.OK) { return; } txtFile.Text = ofd.FileName; } private void btnUnZip_Click(object sender, EventArgs e) { string path = txtFile.Text; string un_dir = Path.GetFileNameWithoutExtension(path);//文件的名称 Directory.CreateDirectory(un_dir); //创建以压缩包为名称的文件夹 ZipInputStream f = new ZipInputStream(File.OpenRead(path)); //读取压缩文件,并用此文件流新建 “ZipInputStream”对象 ZipEntry zp; //获取解压文件流中的项目 while ((zp = f.GetNextEntry()) != null)//循环读取每个文件 { string filePath = Path.Combine(un_dir, zp.Name); string dirPath = Path.GetDirectoryName(filePath); if (!zp.IsDirectory && zp.Crc != 00000000L) //此“ZipEntry”不是“标记文件” { int i = 2048 *2; byte[] b = new byte[i]; //每次缓冲 2048*2 字节 if (!Directory.Exists(dirPath))//存在子文件夹,必须先创建文件夹,否则会报错,无法自动创建文件夹 { Directory.CreateDirectory(dirPath); } FileStream s = File.Create(filePath); //新建文件流 while (true) //持续读取字节,直到一个“ZipEntry”字节读完 { i = f.Read(b, 0, b.Length); //读取“ZipEntry”中的字节 if (i > 0) { s.Write(b, 0, i); //将字节写入新建的文件流 } else { break; //读取的字节为 0 ,跳出循环 } } s.Close(); } } MessageBox.Show("解压缩OK"); }
这个Demo是跑过的,Demo压缩的文件WinRAR是可以打开,其他Zip压缩文件Demo也是可以解压缩的。
如果发现解压缩报错的话,先看看,解压缩的文件是不是zip格式。

浙公网安备 33010602011771号