之前一个同学问了这个问题后,看了园子里其它园友的封装,都很零碎,调用也不是很方便。所以自己就封装了一个zip解压的类。后来想整理下怕自己忘了。就把压缩的类也一并封装了。
c#下压缩解压,主要是用第三方类库进行封装的。ICSharpCode.SharpZipLib.dll类库,链接地址为你官方下载链接。压缩主要是用流的方式进行压缩的。
压缩文件及文件夹。文件压缩很简单,把待压缩的文件用流的方式读到内存中,然后放到压缩流中。就可以了。文件夹就稍微麻烦下了。因为要把待压缩的文件夹解压后保留文件夹文件的层次结构。所以我的实现方式就是 递归遍历文件夹中的文件。计算其相对位置放到压缩流中。
代码如下
-
-
-
-
-
- public bool CompressionZip(string _depositPath)
- {
- bool result = true;
- FileStream fs = null;
- try
- {
- ZipOutputStream ComStream = new ZipOutputStream(File.Create(_depositPath));
- ComStream.SetLevel(9);
- foreach (string path in AbsolutePaths)
- {
-
- if (Directory.Exists(path))
- {
- ZipFloder(path, ComStream, path);
- }
- else if (File.Exists(path))
- {
- fs = File.OpenRead(path);
- byte[] bts = new byte[fs.Length];
- fs.Read(bts, 0, bts.Length);
- ZipEntry ze = new ZipEntry(new FileInfo(path).Name);
- ComStream.PutNextEntry(ze);
- ComStream.Write(bts, 0, bts.Length);
- }
- }
- ComStream.Finish();
- ComStream.Close();
- }
- catch (Exception ex)
- {
- if (fs != null)
- {
- fs.Close();
- }
- errorMsg = ex.Message;
- result = false;
- }
- return result;
- }
-
- private void ZipFloder(string _OfloderPath, ZipOutputStream zos, string _floderPath)
- {
- foreach (FileSystemInfo item in new DirectoryInfo(_floderPath).GetFileSystemInfos())
- {
- if (Directory.Exists(item.FullName))
- {
- ZipFloder(_OfloderPath, zos, item.FullName);
- }
- else if (File.Exists(item.FullName))
- {
- DirectoryInfo ODir = new DirectoryInfo(_OfloderPath);
- string fullName2 = new FileInfo(item.FullName).FullName;
- string path = ODir.Name + fullName2.Substring(ODir.FullName.Length, fullName2.Length - ODir.FullName.Length);
- FileStream fs = File.OpenRead(fullName2);
- byte[] bts = new byte[fs.Length];
- fs.Read(bts, 0, bts.Length);
- ZipEntry ze = new ZipEntry(path);
- zos.PutNextEntry(ze);
- zos.Write(bts, 0, bts.Length);
- }
- }
- }
|