ASP.NET Page

很高兴申请成功了博客园的博客,写篇随笔表示感谢。
今天帮别人做了个项目,功能倒不是很多,但是有些功能比较复杂。比如使用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";
        }

posted @ 2007-05-06 01:59  萧萧空间  阅读(321)  评论(1编辑  收藏  举报