程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> asp.NET中實現文件的壓縮和解壓(3種方式),asp.net3種

asp.NET中實現文件的壓縮和解壓(3種方式),asp.net3種

編輯:關於.NET

asp.NET中實現文件的壓縮和解壓(3種方式),asp.net3種


在.NET可以通過多種方式實現zip的壓縮和解壓:1、使用System.IO.Packaging;2、使用第三方類庫;3、通過 System.IO.Compression 命名空間中新增的ZipArchive、ZipFile等類實現。

一、使用System.IO.Packaging壓縮和解壓

Package為一個抽象類,可用於將對象組織到定義的物理格式的單個實體中,從而實現可移植性與高效訪問。ZIP 文件是Package的主物理格式。 其他Package實現可以使用其他物理格式(如 XML 文檔、數據庫或 Web 服務。與文件系統類似,在分層組織的文件夾和文件中引用 Package 中包含的項。雖然 Package 是抽象類,但 Package.Open 方法默認使用 ZipPackage 派生類。

System.IO.Packaging在WindowsBase.dll程序集下,使用時需要添加對WindowsBase的引用。

 1、將整個文件夾壓縮成zip

 /// <summary>
  /// Add a folder along with its subfolders to a Package
  /// </summary>
  /// <param name="folderName">The folder to add</param>
  /// <param name="compressedFileName">The package to create</param>
  /// <param name="overrideExisting">Override exsisitng files</param>
  /// <returns></returns>
  static bool PackageFolder(string folderName, string compressedFileName, bool overrideExisting)
  {
   if (folderName.EndsWith(@"\"))
    folderName = folderName.Remove(folderName.Length - 1);
   bool result = false;
   if (!Directory.Exists(folderName))
   {
    return result;
   }

   if (!overrideExisting && File.Exists(compressedFileName))
   {
    return result;
   }
   try
   {
    using (Package package = Package.Open(compressedFileName, FileMode.Create))
    {
     var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
     foreach (string fileName in fileList)
     {
      
      //The path in the package is all of the subfolders after folderName
      string pathInPackage;
      pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName);

      Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
      PackagePart packagePartDocument = package.CreatePart(partUriDocument,"", CompressionOption.Maximum);
      using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
      {
       fileStream.CopyTo(packagePartDocument.GetStream());
      }
     }
    }
    result = true;
   }
   catch (Exception e)
   {
    throw new Exception("Error zipping folder " + folderName, e);
   }
   
   return result;
  }

2、將單個文件添加到zip文件中

 /// <summary>
  /// Compress a file into a ZIP archive as the container store
  /// </summary>
  /// <param name="fileName">The file to compress</param>
  /// <param name="compressedFileName">The archive file</param>
  /// <param name="overrideExisting">override existing file</param>
  /// <returns></returns>
  static bool PackageFile(string fileName, string compressedFileName, bool overrideExisting)
  {
   bool result = false;

   if (!File.Exists(fileName))
   {
    return result;
   }

   if (!overrideExisting && File.Exists(compressedFileName))
   {
    return result;
   }

   try
   {
    Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(Path.GetFileName(fileName), UriKind.Relative));
    
    using (Package package = Package.Open(compressedFileName, FileMode.OpenOrCreate))
    {
     if (package.PartExists(partUriDocument))
     {
      package.DeletePart(partUriDocument);
     }

     PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
     using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
     {
      fileStream.CopyTo(packagePartDocument.GetStream());
     }
    }
    result = true;
   }
   catch (Exception e)
   {
    throw new Exception("Error zipping file " + fileName, e);
   }
   
   return result;
  }

3、zip文件解壓

/// <summary>
  /// Extract a container Zip. NOTE: container must be created as Open Packaging Conventions (OPC) specification
  /// </summary>
  /// <param name="folderName">The folder to extract the package to</param>
  /// <param name="compressedFileName">The package file</param>
  /// <param name="overrideExisting">override existing files</param>
  /// <returns></returns>
  static bool UncompressFile(string folderName, string compressedFileName, bool overrideExisting)
  {
   bool result = false;
   try
   {
    if (!File.Exists(compressedFileName))
    {
     return result;
    }

    DirectoryInfo directoryInfo = new DirectoryInfo(folderName);
    if (!directoryInfo.Exists)
     directoryInfo.Create();

    using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read))
    {
     foreach (PackagePart packagePart in package.GetParts())
     {
      ExtractPart(packagePart, folderName, overrideExisting);
     }
    }

    result = true;
   }
   catch (Exception e)
   {
    throw new Exception("Error unzipping file " + compressedFileName, e);
   }
   
   return result;
  }

  static void ExtractPart(PackagePart packagePart, string targetDirectory, bool overrideExisting)
  {
   string stringPart = targetDirectory + HttpUtility.UrlDecode(packagePart.Uri.ToString()).Replace('\\', '/');

   if (!Directory.Exists(Path.GetDirectoryName(stringPart)))
    Directory.CreateDirectory(Path.GetDirectoryName(stringPart));

   if (!overrideExisting && File.Exists(stringPart))
    return;
   using (FileStream fileStream = new FileStream(stringPart, FileMode.Create))
   {
    packagePart.GetStream().CopyTo(fileStream);
   }
  }

使用Package壓縮文件會在zip文件自動生成[Content_Type].xml,用來描述zip文件解壓支持的文件格式。

  <?xml version="1.0" encoding="utf-8" ?> 
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
 <Default Extension="vsixmanifest" ContentType="text/xml" /> 
 <Default Extension="dll" ContentType="application/octet-stream" /> 
 <Default Extension="png" ContentType="application/octet-stream" /> 
 <Default Extension="txt" ContentType="text/plain" /> 
 <Default Extension="pkgdef" ContentType="text/plain" /> 
</Types>

同樣,如果zip文件不包含[Content_Type].xml文件,或者[Content_Type].xml文件不包含所對應擴展名的描述(手動添加的[Content_Type].xml也是可以),將無法解壓文件。

 二、使用第三方類庫

zip的壓縮和解壓使用比較的有SharpZipLib和DotNetZip。

1、SharpZipLib,也稱為“#ziplib”,基於GPL開源,支持Zip,GZip,Tar和BZip2的壓縮和解壓縮。

支持.NET 1.1,NET 2.0(3.5、4.0).

(1)zip壓縮

 public static void Zip(string SrcFile, string DstFile, int BufferSize)
{
 FileStream fileStreamIn = new FileStream
 (SrcFile, FileMode.Open, FileAccess.Read);
 FileStream fileStreamOut = new FileStream
 (DstFile, FileMode.Create, FileAccess.Write);
 ZipOutputStream zipOutStream = new ZipOutputStream(fileStreamOut);
 byte[] buffer = new byte<buffersize />;
 ZipEntry entry = new ZipEntry(Path.GetFileName(SrcFile));
 zipOutStream.PutNextEntry(entry);
 int size;
 do
 {
  size = fileStreamIn.Read(buffer, 0, buffer.Length);
  zipOutStream.Write(buffer, 0, size);
 } while (size > 0);
 zipOutStream.Close();
 fileStreamOut.Close();
 fileStreamIn.Close();
}

(2)解壓zip

  public static void UnZip(string SrcFile, string DstFile, int BufferSize)
{
 FileStream fileStreamIn = new FileStream
 (SrcFile, FileMode.Open, FileAccess.Read);
 ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
 ZipEntry entry = zipInStream.GetNextEntry();
 FileStream fileStreamOut = new FileStream
 (DstFile + @"\" + entry.Name, FileMode.Create, FileAccess.Write);
 int size;
 byte[] buffer = new byte<buffersize />;
 do
 {
  size = zipInStream.Read(buffer, 0, buffer.Length);
  fileStreamOut.Write(buffer, 0, size);
 } while (size > 0);
 zipInStream.Close();
 fileStreamOut.Close();
 fileStreamIn.Close();
}

2、DotNetLib,是基於”WS-PL”開源,使用比較簡單

(1)壓縮

  using (ZipFile zip = new ZipFile())
 {
 zip.AddFile("ReadMe.txt");
 zip.AddFile("7440-N49th.png");
 zip.AddFile("2008_Annual_Report.pdf");  
 zip.Save("Archive.zip");
 }

(2)解壓

 private void MyExtract()
 {
  string zipToUnpack = "C1P3SML.zip";
  string unpackDirectory = "Extracted Files";
  using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
  {
   // here, we extract every entry, but we could extract conditionally
   // based on entry name, size, date, checkbox status, etc. 
   foreach (ZipEntry e in zip1)
   {
   e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
   }
  }
 }

三、在.NET 4.5使用ZipArchive、ZipFile等類壓縮和解壓

 static void Main(string[] args)
  {
   string ZipPath = @"c:\users\exampleuser\start.zip";
   string ExtractPath = @"c:\users\exampleuser\extract";
   string NewFile = @"c:\users\exampleuser\NewFile.txt";

   using (ZipArchive Archive = ZipFile.Open(ZipPath, ZipArchiveMode.Update))
   {
    Archive.CreateEntryFromFile(NewFile, "NewEntry.txt");
    Archive.ExtractToDirectory(ExtractPath);
   } 
  }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持幫客之家。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved