很高興申請成功了部落格園的部落格,寫篇隨筆表示感謝。
今天幫別人做了個項目,功能倒不是很多,但是有些功能比較複雜。比如使用Web頁面對檔案進行壓縮和解壓縮。經過多方面的尋找,使用SharpZipLib實現了壓縮功能。
代碼如下:
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
/// <summary>
/// Zip實現功能壓縮指定檔案夾下的所有檔案
/// </summary>
public class Zip
{
#region 建構函式
/// <summary>
/// 建構函式
/// </summary>
public Zip()
{
//
// TODO: Add constructor logic here
//
}
#endregion
#region 壓縮主函數,實現壓縮功能
/// <summary>
/// 壓縮主函數,實現壓縮功能
/// </summary>
/// <param name="strFileDir"></param>
public void PutInZipFile(string[] strFileDir)
{
string filenames = strFileDir[0];
Crc32 crc = new Crc32();
ZipOutputStream s = new ZipOutputStream(File.Create(args[1]));
s.SetLevel(6);
foreach (string file in Directory.GetFiles(filenames))
{
FileStream fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string[] strName = file.Split('\\');
ZipEntry entry = new ZipEntry(strName[strName.Length - 1]);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
s.Finish();
s.Close();
}
#endregion
}
調用此類中的方法,就可以將指定檔案夾中的所有檔案壓縮成.zip檔案。
if (!IsPostBack)
{
string[] FileProperties = new string[2];
string fullName = Server.MapPath("Upload");
string destPath = System.IO.Path.GetDirectoryName(fullName);
//待壓縮檔
FileProperties[0] = fullName;
//壓縮後的目標檔案
FileProperties[1] = destPath + string.Format("\\{0}.zip", "XXX");
if (File.Exists(FileProperties[1]))
{
File.Delete(FileProperties[1]);
}
Zip Zc = new ZipClass();
Zc.PutInZipFile(FileProperties);
this.downFile.HRef = string.Format("/upload/{0}.zip", "XXX");
this.downFile.Target = "_blank";
}