之前都是想到用Process直接呼叫壓縮程式直接壓縮就好了

不過有印象還是有其他的方式

就找了一點人家寫的東東......

找到了下面這二個

DotNetZip :http://www.codeplex.com/DotNetZip

我抓的時候是1.9版了.....裡面包了範例等等的東西

2010090701.jpg

SharpZip :http://www.icsharpcode.net/OpenSource/SharpZipLib/

直接DownLoadDLL應該就可以了不然裡面也是有範例程式

2010090702.jpg

第一種方式如下:

 protected void Button3_Click(object sender, EventArgs e)
    {
        MyZipFile();
        //壓縮後直接下載檔案
        FileStream fileStream = new FileStream("D:\\DotNetZip.zip", FileMode.Open);
        long fileSize = fileStream.Length;
        Response.ContentType = "application/zip";
        Response.AddHeader("Content-Disposition", "attachment; filename=DotNetZip.zip");
        Response.AddHeader("Content-Length", fileSize.ToString());
        byte[] fileBuffer = new byte[fileSize];
        fileStream.Read(fileBuffer, 0, (int)fileSize);
        Response.BinaryWrite(fileBuffer);
        Response.End();
    }
 //壓縮
 private void MyZipFile()
    {
        string path = HttpContext.Current.Request.MapPath("Zip");

        IEnumerable filelist = GetFiles(path);

        var files = from f in filelist where f.Extension == ".bat" select f;

        //DotNetZip壓縮輸出檔案
        if (files.Count() > 0)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(System.Text.Encoding.Default))
            {
                zip.Password = "123456!";
                foreach (var f in files)
                {
                    zip.AddFile(f.FullName, "");
                }
                zip.Save("D:\\DotNetZip.zip");
                zip.Dispose();
            }

        }
    }
 //取得檔案
 private static IEnumerable GetFiles(string path)
    {
        string[] filenames = null;
        List files = new List();

        filenames = System.IO.Directory.GetFiles(path, "*.*", System.IO.SearchOption.AllDirectories);

        foreach (string name in filenames)
        {
            files.Add(new System.IO.FileInfo(name));
        }

        return files;
    }
//解壓縮
protected void Button4_Click(object sender, EventArgs e)
    {
        MyUnZipFile();
    }
private void MyUnZipFile()
    {
        using (Ionic.Zip.ZipFile DotZip = Ionic.Zip.ZipFile.Read("D:\\DotNetZip.zip", System.Text.Encoding.Default))
        {
            DotZip.Password = "123456!";
            DotZip.ExtractAll("D:\\");
        }

    }

第二種方式如下:

//取得專案路徑Zip目錄下所有含子目錄的檔案
private List GetFiles()
{
   List lstFileInfo = new List();
   string dir = Server.MapPath("Zip");
   FileInfo info;
   string[] files;
   //取得dir下所有的檔案子目錄下的檔案
   files = Directory.GetFiles(dir,"*.*",System.IO.SearchOption.AllDirectories);
   foreach (string item in files)
   {
       info = new FileInfo(item);
       //取得今天被寫入的檔案
       //if (info.LastWriteTime.ToString("yyyyMMdd") == DateTime.Now.ToString("yyyyMMdd"))
       //{
           lstFileInfo.Add(info);
       //}
   }
   return lstFileInfo;
}

//DotNetZip的壓縮方式
protected void btnDotNetZip_Click(object sender, EventArgs e)
{
    //DotNetZip壓縮輸出檔案
    List lstSelected = GetFiles();
    if (lstSelected.Count > 0)
    {
        Response.Clear();
        Response.ContentType = "application/zip";
        Response.AddHeader("content-disposition", "filename=" + "DotNetZip.zip");
        using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(System.Text.Encoding.Default))
        {
            foreach (FileInfo file in lstSelected)
            {
                zip.AddFile(file.FullName, "");
            }
            zip.Save(Response.OutputStream);
                zip.Dispose();
        }
        Response.End();
    }
}
//SharpZip的壓縮方式
protected void btnSharpZip_Click(object sender, EventArgs e)
{
   //SharpZip壓縮輸出檔案
   List lstSelected = GetFiles();
   if (lstSelected.Count > 0)
   {
       Response.Clear();
       Response.ContentType = "application/zip";
       Response.AddHeader("content-disposition", "filename=" + "SharpZip.zip");
       using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(Response.OutputStream))
       {
           foreach (FileInfo file in lstSelected)
           {
               AddZipEntry(zip,"", file.FullName);
           }
           zip.Finish();
           zip.IsStreamOwner = false;// 避免 stream 被 zip 物件關閉
       }
       Response.End();
   }
}

//SharpZip
private static void AddZipEntry(ICSharpCode.SharpZipLib.Zip.ZipOutputStream zip, string folder, string filename)
{
    if (System.IO.Directory.Exists(filename) == true)
    {            
        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(filename);
        string folder_ = folder + di.Name + "/";
        ICSharpCode.SharpZipLib.Zip.ZipEntry zFolder = new ICSharpCode.SharpZipLib.Zip.ZipEntry(folder_);
        zip.PutNextEntry(zFolder);
        foreach (System.IO.DirectoryInfo d in di.GetDirectories())
            AddZipEntry(zip, folder_, d.FullName);
        foreach (System.IO.FileInfo f in di.GetFiles())
            AddZipEntry(zip, folder_, f.FullName);
    }
    else if (System.IO.File.Exists(filename) == true)
    {
        // File
        zip.SetLevel(9);
        using (System.IO.FileStream fs = System.IO.File.OpenRead(filename))
        {
            byte[] b = new byte[fs.Length];
            fs.Read(b, 0, b.Length);
            ICSharpCode.SharpZipLib.Zip.ZipEntry z = new ICSharpCode.SharpZipLib.Zip.ZipEntry(folder + new System.IO.FileInfo(filename).Name);
            zip.PutNextEntry(z);
            zip.Write(b, 0, b.Length);
        }
    }
}

第三種方式如下:

protected void Button1_Click(object sender, EventArgs e)
{
    //壓縮
    ZipFiles("D:\\Zip","D:\\ICSharp.zip","12345");
    //解壓縮
    UnZipFiles("D:\\ICSharp.zip","D:\\","12345");
}

//壓縮
public static void ZipFiles(string FolderPath, string PathAndFile, string password)
    {
        //讀取檔案
        ArrayList ar = GetFileList(FolderPath);

        int TrimLength = (Directory.GetParent(FolderPath)).ToString().Length;
        
        TrimLength += 1; 
        FileStream ostream;
        byte[] obuffer;
        ICSharpCode.SharpZipLib.Zip.ZipOutputStream oZipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(PathAndFile)); 

        if (password != null && password != String.Empty)
            oZipStream.Password = password;

        oZipStream.SetLevel(9); 
        ICSharpCode.SharpZipLib.Zip.ZipEntry oZipEntry;
        foreach (string Fil in ar) 
        {
            oZipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Fil.Remove(0, TrimLength));
            oZipStream.PutNextEntry(oZipEntry);

            if (!Fil.EndsWith(@"/")) 
            {
                ostream = File.OpenRead(Fil);
                obuffer = new byte[ostream.Length];
                ostream.Read(obuffer, 0, obuffer.Length);
                oZipStream.Write(obuffer, 0, obuffer.Length);
            }
        }
        oZipStream.Finish();
        oZipStream.Close();
    }
//取得檔案(包含所有子目錄及子目錄下的檔案)
private static ArrayList GetFileList(string Dir)
    {
        ArrayList fils = new ArrayList();
        bool Empty = true;
        foreach (string file in Directory.GetFiles(Dir)) 
        {
            fils.Add(file);
            Empty = false;
        }

        if (Empty)
        {
            if (Directory.GetDirectories(Dir).Length == 0)                        
                fils.Add(Dir + @"/");
            
        }

        foreach (string dirs in Directory.GetDirectories(Dir)) 
        {
            foreach (object obj in GetFileList(dirs))
            {
                fils.Add(obj);
            }
        }
        return fils; 
    }
//解壓縮
public static void UnZipFiles(string zipPathAndFile, string outputFolder, string password)
    {
        ICSharpCode.SharpZipLib.Zip.ZipInputStream s = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(zipPathAndFile));
        if (password != null && password != String.Empty)
            s.Password = password;
        ICSharpCode.SharpZipLib.Zip.ZipEntry theEntry;
        string tmpEntry = String.Empty;
        while ((theEntry = s.GetNextEntry()) != null)
        {
            string directoryName = outputFolder;
            string fileName = Path.GetFileName(theEntry.Name);
          
            if (directoryName != "")
            {
                Directory.CreateDirectory(directoryName);
            }
            if (fileName != String.Empty)
            {
                if (theEntry.Name.IndexOf(".ini") < 0)
                {
                    string fullPath = directoryName + "\\" + theEntry.Name;
                    fullPath = fullPath.Replace("\\ ", "\\");
                    string fullDirPath = Path.GetDirectoryName(fullPath);
                    if (!Directory.Exists(fullDirPath)) Directory.CreateDirectory(fullDirPath);
                    FileStream streamWriter = File.Create(fullPath);
                    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
                        {
                            break;
                        }
                    }
                    streamWriter.Close();
                }
            }
        }
        s.Close();      
    }

參考:http://www.dotblogs.com.tw/puma/archive/2009/05/30/asp.net-dotnetzip-sharpzip-io-fileinfo-directory.aspx

參考:http://richielin-programer.blogspot.com/2008/04/c-sharpzip.html

參考:http://blog.miniasp.com/post/2009/01/11/Introduce-SharpZipLib-and-DotNetZip-Library-for-NET.aspx#continue

參考:http://www.eggheadcafe.com/community/aspnet/2/10060149/zip-a-file-using-icsharpcodesharpziplibzip.aspx

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 鴨爸 的頭像
    鴨爸

    鴨爸的隨手寫寫

    鴨爸 發表在 痞客邦 留言(0) 人氣()