c# 解压缩文件(.jar与.zip)的代码

发布时间:2019-08-02编辑:脚本学堂
c#实现的解压缩.zip文件的代码,当然解压.jar也是没有问题的,如果你正在寻找解压.zip的代码,这个可以参考下。

c# 解压缩.zip文件的代码。

复制代码 代码示例:

/// <summary>
/// 解压缩 zip 文件
/// </summary>
/// <param name="zipFileName">要解压的 zip 文件</param>
/// <param name="extractLocation">zip 文件的解压目录</param>
/// <param name="password">zip 文件的密码。</param>
/// <param name="overWrite">是否覆盖已存在的文件。</param>
private void UnZipDir(string zipFileName, string extractLocation, string password, bool overWrite)
{
  string myExtractLocation = extractLocation;
  if (myExtractLocation == "")
      myExtractLocation = Directory.GetCurrentDirectory();
  if (!myExtractLocation.EndsWith(@"/"))
      myExtractLocation = myExtractLocation + @"/";
  ZipInputStream s = new ZipInputStream(File.OpenRead(zipFileName));
  s.Password = password;
  ZipEntry theEntry;
      
  while ((theEntry = s.GetNextEntry()) != null)//判断下一个zip 接口是否未空
  {
      string directoryName = "";
      string pathToZip = "";
      pathToZip = theEntry.Name;

      if (pathToZip != "")
   directoryName = Path.GetDirectoryName(pathToZip) + @"/";
      string fileName = Path.GetFileName(pathToZip);
      Directory.CreateDirectory(myExtractLocation + directoryName);
      if (fileName != "")
      {
   try
   {
       if ((File.Exists(myExtractLocation + directoryName + fileName) && overWrite) || (!File.Exists(myExtractLocation + directoryName + fileName)))
       {
    FileStream streamWriter = File.Create(myExtractLocation + directoryName + fileName);
    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;
    }
    streamWriter.Close();
       }
   }
   catch (ZipException ex)
   {
       FileStream fs = new FileStream(AppDomain.CurrentDomain.Basedirectory + "log.txt", FileMode.OpenOrCreate, FileAccess.Write);
       StreamWriter sw = new StreamWriter(fs);
       sw.WriteLine(ex.Message);
   }
      }
  }
  s.Close();
}