這里筆者為大家介紹在asp.net中使用文件的壓縮與解壓。在asp.net中使用壓縮給大家帶來的好處是顯而易見的,首先是減小了服務器端文件存儲的空間,其次下載時候下載的是壓縮文件想必也會有效果吧,特別是比較大的文件。有的客戶可能會很粗心上傳的是文件,那么可以通過判斷后綴名來判斷文件,不是壓縮文件,就可以壓縮文件,在存儲。
這里筆者引用了一個DLL文件(ICSharpCode.SharpZipLib.dll)(包含在本文代碼中),調用其中的函數,就可以對文件進行壓縮及解壓了。其中壓縮筆者主要用到的函數是
C# Code復制內容到剪貼板
- // <summary>
- /// 壓縮文件
- /// </summary>
- /// <param name="fileName">要壓縮的所有文件(完全路徑)</param>
- /// <param name="name">壓縮后文件路徑</param>
- /// <param name="Level">壓縮級別</param>
- public void ZipFileMain(string[] filenames, string name, int Level)
- {
- ZipOutputStream s = new ZipOutputStream(File.Create(name));
- Crc32 crc = new Crc32();
- //壓縮級別
- s.SetLevel(Level); // 0 - store only to 9 - means best compression
- try
- {
- foreach (string file in filenames)
- {
- //打開壓縮文件 FileStream fs = File.OpenRead(file);
- byte[] buffer = new byte[fs.Length];
- fs.Read(buffer, 0, buffer.Length);
- //建立壓縮實體 ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(file));
- //時間 entry.DateTime = DateTime.Now;
- // set Size and the crc, because the information
- // about the size and crc should be stored in the header
- // if it is not set it is automatically written in the footer.
- // (in this case size == crc == -1 in the header) // Some ZIP programs have problems with zip files that don't store
- // the size and crc in the header.
- //空間大小 entry.Size = fs.Length;
- fs.Close();
- crc.Reset();
- crc.Update(buffer);
- entry.Crc = crc.Value;
- s.Write(buffer, 0, buffer.Length);
- }
- }
- catch
- {
- throw;
- }
- finally
- {
- s.Finish();
- s.Close();
- }
- }
解壓縮的主要代碼
C# Code復制內容到剪貼板
- /// <summary>
- /// 解壓文件
- /// </summary>
- /// <param name="ZipPath">被解壓的文件路徑</param>
- /// <param name="Path">解壓后文件的路徑</param>
- public void UnZip(string ZipPath,string Path)
- {
- ZipInputStream s = new ZipInputStream(File.OpenRead(ZipPath));
- ZipEntry theEntry;
- try
- while ((theEntry = s.GetNextEntry()) != null)
- {
- string fileName = System.IO.Path.GetFileName(theEntry.Name);
- //生成解壓目錄 Directory.CreateDirectory(Path);
- if (fileName != String.Empty)
- {
- //解壓文件 FileStream streamWriter = File.Create(Path + 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
- {
- streamWriter.Close();
- streamWriter.Dispose();
- break;
- } }
- streamWriter.Close();
- streamWriter.Dispose();
- }
- }
- }
- catch
- {
- throw;
- }
- finally
- {
- s.Close();
- s.Dispose();
- }
- }
- }
我這里做了個簡單的測試程序(點擊下載)
這里已知道要被壓縮文件,這里只需填入要被壓縮到的路徑("D:\text\")解壓路徑一樣。這里解壓級別越大,壓縮的就越厲害。
可以看測試小程序,將解壓/壓縮引入到你的項目中。