c#使用SharpZipLib壓縮和解壓縮文件

本文是在其他人基礎上修改而來,測試過程:原文地址

正常zip方式壓縮文件,然後用wrar工具可以解壓出來(開始用wrar3.4版本的怎麼也解不出來,以爲是不支持wrar解壓,後來改用3.9及4.11版本可以實現正常解壓,搞了半天時間,原來是版本問題,版本不對害死人啊),另外wrar壓縮時選擇“zip”選項壓縮時,再用此類進行解壓,也可以正常解壓。

在此以做標記,給自己個別人做鋪路,以後少走彎路,

如下列出代碼,至於dll自己可以去下載,屬於開源類庫。

調用方式,如下:

[csharp] view plaincopyprint?

    private void btnNewZip_Click(object sender, EventArgs e)  
           {  
               try  
               {  
                   Common.SharpZipLibHelper zip = new Common.SharpZipLibHelper();  
                   //zip.Compress(@"c:\789A", @"c:\789A.zip", true);  
                   zip.Compress(@"c:\db.mdb", @"c:\db.zip", true);  
               }  
               catch { }  
           }  
      
           private void btnNewUnZip_Click(object sender, EventArgs e)  
           {  
               try  
               {  
                   Common.SharpZipLibHelper zip = new Common.SharpZipLibHelper();  
                   //zip.UnZipDirectory(@"c:\789A.zip", @"c:\789test", "");  
                   zip.UnZipDirectory(@"c:\db.zip", @"c:\dbaa", "");  
               }  
               catch { }  
           }  



以下是helper類庫,當中修改了一個地方:


[csharp] view plaincopyprint?

    <p>using System;</p><pre class="csharp" name="code">using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
    using System.IO;  
    using ICSharpCode.SharpZipLib.Zip;  
    using ICSharpCode.SharpZipLib.Checksums;  
      
    namespace Common  
    {  
        public class SharpZipLibHelper  
        {  
            private byte[] buffer = new byte[2048];  
     
            #region 壓縮文件夾,支持遞歸  
      
            /// <summary>  
            /// 壓縮文件夾  
            /// </summary>  
            /// <param name="dir">待壓縮的文件夾</param>  
            /// <param name="targetFileName">壓縮後文件路徑(包括文件名)</param>  
            /// <param name="recursive">是否遞歸壓縮</param>  
            /// <returns></returns>  
            public bool Compress(string dir, string targetFileName, bool recursive)  
            {  
                //如果已經存在目標文件,詢問用戶是否覆蓋  
                if (File.Exists(targetFileName))  
                {  
                    // if (!_ProcessOverwrite(targetFileName))  
                    return false;  
                }  
                string[] ars = new string[2];  
                if (recursive == false)  
                {  
                    //return Compress(dir, targetFileName);  
                    ars[0] = dir;  
                    ars[1] = targetFileName;  
                    return ZipFileDictory(ars);  
                }  
                FileStream ZipFile;  
                ZipOutputStream ZipStream;  
      
                //open  
                ZipFile = File.Create(targetFileName);  
                ZipStream = new ZipOutputStream(ZipFile);  
      
                if (dir != String.Empty)  
                {  
                    _CompressFolder(dir, ZipStream, dir.Substring(3));  
                }  
      
                //close  
                ZipStream.Finish();  
                ZipStream.Close();  
      
                if (File.Exists(targetFileName))  
                    return true;  
                else  
                    return false;  
            }  
      
      
      
      
      
            /// <summary>  
            /// 壓縮目錄  
            /// </summary>  
            /// <param name="args">數組(數組[0]: 要壓縮的目錄; 數組[1]: 壓縮的文件名)</param>  
            public static bool ZipFileDictory(string[] args)  
            {  
                ZipOutputStream s = null;  
                try  
                {  
                    string[] filenames = Directory.GetFiles(args[0]);  
      
                    Crc32 crc = new Crc32();  
                    s = new ZipOutputStream(File.Create(args[1]));  
                    s.SetLevel(6);  
      
                    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(file);  
      
                        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);  
      
                    }  
      
                }  
                catch (Exception e)  
                {  
                    return false;  
                }  
      
                finally  
                {  
                    s.Finish();  
                    s.Close();  
                }  
                return true;  
            }  
      
      
      
      
      
            /// <summary>  
            /// 壓縮某個子文件夾  
            /// </summary>  
            /// <param name="basePath"></param>  
            /// <param name="zips"></param>  
            /// <param name="zipfolername"></param>       
            private static void _CompressFolder(string basePath, ZipOutputStream zips, string zipfolername)  
            {  
                if (File.Exists(basePath))  
                {  
                    _AddFile(basePath, zips, zipfolername);  
                    return;  
                }  
                string[] names = Directory.GetFiles(basePath);  
                foreach (string fileName in names)  
                {  
                    _AddFile(fileName, zips, zipfolername);  
                }  
      
                names = Directory.GetDirectories(basePath);  
                foreach (string folderName in names)  
                {  
                    _CompressFolder(folderName, zips, zipfolername);  
                }  
      
            }  
      
            /// <summary>  
            /// 壓縮某個子文件  
            /// </summary>  
            /// <param name="fileName"></param>  
            /// <param name="zips"></param>  
            /// <param name="zipfolername"></param>  
            private static void _AddFile(string fileName, ZipOutputStream zips, string zipfolername)  
            {  
                if (File.Exists(fileName))  
                {  
                    _CreateZipFile(fileName, zips, zipfolername);  
                }  
            }  
      
            /// <summary>  
            /// 壓縮單獨文件  
            /// </summary>  
            /// <param name="FileToZip"></param>  
            /// <param name="zips"></param>  
            /// <param name="zipfolername"></param>  
            private static void _CreateZipFile(string FileToZip, ZipOutputStream zips, string zipfolername)  
            {  
                try  
                {  
                    FileStream StreamToZip = new FileStream(FileToZip, FileMode.Open, FileAccess.Read);  
                    string temp = FileToZip;  
                    string temp1 = zipfolername;  
                    if (temp1.Length > 0)  
                    {  
                        int i = temp1.LastIndexOf("\\") + 1;//這個地方原來是個bug用的是"//",導致壓縮路徑過長路徑2012-7-2  
                        int j = temp.Length - i;  
                        temp = temp.Substring(i, j);  
                    }  
                    ZipEntry ZipEn = new ZipEntry(temp.Substring(3));  
      
                    zips.PutNextEntry(ZipEn);  
                    byte[] buffer = new byte[16384];  
                    System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);  
                    zips.Write(buffer, 0, size);  
                    try  
                    {  
                        while (size < StreamToZip.Length)  
                        {  
                            int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);  
                            zips.Write(buffer, 0, sizeRead);  
                            size += sizeRead;  
                        }  
                    }  
                    catch (System.Exception ex)  
                    {  
                        throw ex;  
                    }  
      
                    StreamToZip.Close();  
                }  
                catch (Exception e)  
                {  
                    throw e;  
                }  
            }  
            #endregion  
     
     
     
            #region  
      
            /// <summary>  
            /// 解壓縮目錄  
            /// </summary>  
            /// <param name="zipDirectoryPath">壓縮目錄路徑</param>  
            /// <param name="unZipDirecotyPath">解壓縮目錄路徑</param>  
            public void UnZipDirectory(string zipDirectoryPath, string unZipDirecotyPath, string Password)  
            {  
                while (unZipDirecotyPath.LastIndexOf("\\") + 1 == unZipDirecotyPath.Length)//檢查路徑是否以"\"結尾  
                {  
                    unZipDirecotyPath = unZipDirecotyPath.Substring(0, unZipDirecotyPath.Length - 1);//如果是則去掉末尾的"\"  
                }  
      
                using (ZipInputStream zipStream = new ZipInputStream(File.OpenRead(zipDirectoryPath)))  
                {  
      
                    //判斷Password  
                    if (Password != null && Password.Length > 0)  
                    {  
                        zipStream.Password = Password;  
                    }  
      
                    ZipEntry zipEntry = null;  
                    while ((zipEntry = zipStream.GetNextEntry()) != null)  
                    {  
                        string directoryName = Path.GetDirectoryName(zipEntry.Name);  
                        string fileName = Path.GetFileName(zipEntry.Name);  
      
                        if (!string.IsNullOrEmpty(directoryName))  
                        {  
                            Directory.CreateDirectory(unZipDirecotyPath + @"\" + directoryName);  
                        }  
      
                        if (!string.IsNullOrEmpty(fileName))  
                        {  
                            if (zipEntry.CompressedSize == 0)  
                                break;  
                            if (zipEntry.IsDirectory)//如果壓縮格式爲文件夾方式壓縮  
                            {  
                                directoryName = Path.GetDirectoryName(unZipDirecotyPath + @"\" + zipEntry.Name);  
                                Directory.CreateDirectory(directoryName);  
                            }  
                           else//2012-5-28修改,支持單個文件壓縮時自己創建目標文件夾  
                            {  
                                if (!Directory.Exists(unZipDirecotyPath))  
                                {  
                                    Directory.CreateDirectory(unZipDirecotyPath);  
                                }  
                            }  
      
                            using (FileStream stream = File.Create(unZipDirecotyPath + @"\" + zipEntry.Name))  
                            {  
                                while (true)  
                                {  
                                    int size = zipStream.Read(buffer, 0, buffer.Length);  
                                    if (size > 0)  
                                    {  
                                        stream.Write(buffer, 0, size);  
                                    }  
                                    else  
                                    {  
                                        break;  
                                    }  
                                }  
                            }  
                        }  
                    }  
                }  
            }  
     
     
            #endregion  
      
      
        }  
    }  
    </pre><br>  
    <br>  
    <p></p>  
    <p></p>  
    <p><br>  
    </p>  
    <pre></pre>  
    <pre></pre>  
    <pre></pre>  
    <pre></pre>  
    <pre></pre>  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章