当前位置: 移动技术网 > IT编程>开发语言>c# > c# 文件压缩zip或将zip文件解压的方法

c# 文件压缩zip或将zip文件解压的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

1.必须dll:

icsharpcode.sharpziplib.dll。可从nutget程序包中获取。

2.压缩文件

/// <summary>
/// 压缩文件成zip
/// </summary>
/// <param name="filezip">压缩成zip文件的绝对路径</param>
/// <param name="filename">被压缩指定文件的名字</param>
/// <param name="zipfilepath"></param>
/// <returns></returns>
public bool createzipfile(string filezip,string filename, string zipfilepath)
  {
   bool iszip = false;
   if (!directory.exists(zipfilepath))
   {
    logger.info($"cannot find directory {zipfilepath}", false, "filetozip");
    return iszip;
   }
   try
   {
    string[] filenames = directory.getfiles(zipfilepath);
    using (zipoutputstream s = new zipoutputstream(file.create(filezip)))
    {
     s.setlevel(9); // 压缩级别 0-9
     //s.password = "123"; //zip压缩文件密码
     byte[] buffer = new byte[4096]; //缓冲区大小
     foreach (string file in filenames.tolist())
     {
      if (file== zipfilepath+filename)//指定被压缩文件的绝对路径
      {
       zipentry entry = new zipentry(path.getfilename(file));
       entry.datetime = datetime.now;
       s.putnextentry(entry);
       using (filestream fs = file.openread(file))
       {
        int sourcebytes;
        do
        {
         sourcebytes = fs.read(buffer, 0, buffer.length);
         s.write(buffer, 0, sourcebytes);
        } while (sourcebytes > 0);
        fs.close();
        fs.dispose();
       }
       break;
      }
     }
     s.finish();
     s.close();
     iszip = true;
    }
   }
   catch (exception ex)
   {
    logger.info($"exception during processing {0}", false, "filetozip");
   }
   return iszip;
  }

3.将zip文件解压

/// <summary>
/// 解压文件
/// </summary>
/// <param name="zipfilepath">压缩文件的绝对路径</param>
 public void unzipfile(string zipfilepath)
  {
   if (!file.exists(zipfilepath))
   {
    logger.info($"cannot find file {zipfilepath}", false, "filetozip");
    return;
   }
   using (zipinputstream s = new zipinputstream(file.openread(zipfilepath)))
   {
    zipentry theentry;
    while ((theentry = s.getnextentry()) != null)
    {
     string directoryname = path.getdirectoryname(theentry.name);
     string filename = path.getfilename(theentry.name);
     // create directory
     if (directoryname?.length > 0)
     {
      directory.createdirectory(directoryname);
     }
     if (!string.isnullorempty(filename))
     {
      using (filestream streamwriter = file.create(theentry.name))
      {
       int size = 2048;
       byte[] data = new byte[2048];
       while (true)
       {
        size = s.read(data, 0, data.length);
        if (size > 0)
        {
         streamwriter.write(data, 0, size);
        }
        else
        {
         break;
        }
       }
      }
     }
    }
   }
  }

4.其它:其中的logger是log4的用法。

以上这篇c# 文件压缩zip或将zip文件解压的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网