C#加压解压方法分享

需要引用ICSharpCode.SharpZipLib.dll

/// <summary>
/// 将文件压缩成zip格式
/// </summary>
/// <param name="zipFile">zip压缩文件的完整路径</param>
/// <param name="sourcePaths">要压缩的文件夹和文件的完整路径的字符串数组</param>
public static void Compress(string zipFile, params string[] sourcePaths)
{
  fileNameList = new List<string>();
  zipFileDir = new List<string>();

  for (int i = 0; i < sourcePaths.Length; i++)
  {
    if (new FileInfo(sourcePaths[i]).Attributes == FileAttributes.Directory)//如果是个目录
    {
      //判断目录是否存在
      if (Directory.Exists(sourcePaths[i]))
      {
        partFileDir = sourcePaths[i].Substring(0, sourcePaths[i].LastIndexOf("\\") + 1);
        GetDirAndChildDirFileNames(sourcePaths[i]);
      }
      else
      {
        throw new System.IO.DirectoryNotFoundException("指定的目录:" + sourcePaths[i] + "不存在!");
      }
    }
    else//如果是单独的文件
    {
      fileNameList.Add(sourcePaths[i]);
      zipFileDir.Add(sourcePaths[i].Substring(sourcePaths[i].LastIndexOf("\\") + 1));
    }
  }
  //string radomFileName = Path.GetRandomFileName();
  //string fullTempFileName = GetTempPath() + radomFileName.Remove(radomFileName.LastIndexOf(".") + 1) + "zip";
  if (File.Exists(zipFile))
  {
    File.Delete(zipFile);
  }
  if (!File.Exists(zipFile))
  {

    //压缩文件不存在,新建
    using (ZipOutputStream zops = new ZipOutputStream(File.Create(zipFile)))
    {
      zops.SetLevel(6);
      for (int i = 0; i < fileNameList.Count; i++)
      {
        try
        {
          if (File.Exists(fileNameList[i]))
          {
            using (FileStream fs = File.OpenRead(fileNameList[i]))
            {
              ZipEntry entry = new ZipEntry(zipFileDir[i]);
              entry.DateTime = System.DateTime.Now;
              entry.Size = fs.Length;
              zops.PutNextEntry(entry);
              byte[] buffer = new byte[2048];
              int readSize = 0;
              do
              {
                readSize = fs.Read(buffer, 0, buffer.Length);
                zops.Write(buffer, 0, readSize);
              }
              while (readSize > 0);
              fs.Close();
            }
          }
        }
        catch
        {
          try
          {
            zops.Finish();
            zops.Close();
            File.Delete(zipFile);
            throw new Exception("压缩过程中产生错误!压缩失败!");
          }
          catch
          {
            throw new Exception("删除压缩文件失败!");
          }
        }
      }
      zops.Finish();
      zops.Close();
      //File.Move(fullTempFileName, zipFile);
    }
  }
  else
  {
    //抛出异常
    throw new System.Exception("同名压缩文件已存在,压缩文件失败!");
  }
}

/// <summary>
/// 解压缩zip文件
/// </summary>
/// <param name="zipFile">zip文件完整路径</param>
/// <param name="targetPath">目标文件夹,压缩文件将解压在该目录下</param>
public static void Decompress(string zipFile, string targetPath)
{
  //string radomName = Path.GetRandomFileName();
  //string radomDirName = GetTempPath() + radomName.Remove(radomName.LastIndexOf("."));
  //if (!radomDirName.EndsWith("\\"))
  //{
    // radomDirName += "\\";
  //}
  //if (!Directory.Exists(radomDirName))
  //{
    // Directory.CreateDirectory(radomDirName);
  //}
  if (!targetPath.EndsWith("\\"))
  {
    targetPath += "\\";
  }
  //如果目标文件夹不存在,创建目标文件夹
  if (!Directory.Exists(targetPath))
  {
    Directory.CreateDirectory(targetPath);
  }
  else
  {
    //删除
    //Directory.Delete(targetPath, true);
    //重新创建
    //Directory.CreateDirectory(targetPath);
  }
  if (File.Exists(zipFile))
  {
    using (ZipInputStream zis = new ZipInputStream(File.OpenRead(zipFile)))
    {
      ZipEntry entry;
      try
      {
        while ((entry = zis.GetNextEntry()) != null)
        {
          string zipDirName = Path.GetDirectoryName(entry.Name);
          string zipFileName = Path.GetFileName(entry.Name);
          if (!Directory.Exists(targetPath + zipDirName) && zipDirName.Length > 0)
          {
            Directory.CreateDirectory(targetPath + zipDirName);
          }
          if (!string.IsNullOrEmpty(zipFileName))
          {
            using (FileStream fs = File.Create(targetPath + entry.Name))
            {
              int readSize = 0;
              byte[] buffer = new byte[2048];
              while (true)
              {
                readSize = zis.Read(buffer, 0, buffer.Length);
                if (readSize > 0)
                {
                  fs.Write(buffer, 0, readSize);
                }
                else
                {
                  break;
                }
              }
              fs.Close();
            }
          }
        }
      }
      catch(Exception err)
      {
        zis.Close();
        //Directory.Delete(targetPath, true);
        throw new System.Exception("解压缩过程中产生错误!解压缩文件失败!" + err.Message + err.Source + err.StackTrace);
      }

    }
  }
  else
  {
    throw new System.IO.FileNotFoundException("未找到指定的zip压缩文件!");
  }
}

//获取当前目录及子目录下的所有文件
private static void GetDirAndChildDirFileNames(string DirName)
{
  foreach (string fileName in Directory.GetFiles(DirName))
  {
    fileNameList.Add(fileName);
    zipFileDir.Add(fileName.Replace(partFileDir, ""));
  }
  foreach (string filePath in Directory.GetDirectories(DirName))
  {
    GetDirAndChildDirFileNames(filePath);
  }
}

posted @ 2021-06-21 09:12  fusr  阅读(177)  评论(0)    收藏  举报