1. 程式人生 > >C#使用SharpZipLib壓縮單個檔案

C#使用SharpZipLib壓縮單個檔案

引入:

using ICSharpCode.SharpZipLib.Zip;

壓縮檔案:

        /// <summary>
        /// ZIP壓縮單個檔案
        /// </summary>
        /// <param name="sFileToZip">需要壓縮的檔案(絕對路徑)</param>
        /// <param name="sZippedPath">壓縮後的檔案路徑(絕對路徑)</param>
        /// <param name="sZippedFileName">壓縮後的檔名稱(檔名,預設 同源檔案同名)</param>
        /// <param name="nCompressionLevel">壓縮等級(0 無 - 9 最高,預設 5)</param>
        /// <param name="nBufferSize">快取大小(每次寫入檔案大小,預設 2048)</param>
        /// <param name="bEncrypt">是否加密(預設 加密)</param>
        /// <param name="sPassword">密碼(設定加密時生效。預設密碼為"123")</param>
        public static string ZipFile(string sFileToZip, string sZippedPath, string sZippedFileName = "", int nCompressionLevel = 5, int nBufferSize = 2048, bool bEncrypt = true,string sPassword="123")
        {
            if (!File.Exists(sFileToZip))
            {
                return null;
            }
            string sZipFileName = string.IsNullOrEmpty(sZippedFileName) ? sZippedPath + "\\" + new FileInfo(sFileToZip).Name.Substring(0, new FileInfo(sFileToZip).Name.LastIndexOf('.')) + ".zip" : sZippedPath + "\\" + sZippedFileName + ".zip";
            using (FileStream aZipFile = File.Create(sZipFileName))
            {
                using (ZipOutputStream aZipStream = new ZipOutputStream(aZipFile))
                {
                    using (FileStream aStreamToZip = new FileStream(sFileToZip, FileMode.Open, FileAccess.Read))
                    {
                        string sFileName = sFileToZip.Substring(sFileToZip.LastIndexOf("\\") + 1);
                        ZipEntry ZipEntry = new ZipEntry(sFileName);
                        if (bEncrypt)
                        {
                            aZipStream.Password = sPassword;
                        }
                        aZipStream.PutNextEntry(ZipEntry);
                        aZipStream.SetLevel(nCompressionLevel);
                        byte[] buffer = new byte[nBufferSize];
                        int sizeRead = 0;
                        try
                        {
                            do
                            {
                                sizeRead = aStreamToZip.Read(buffer, 0, buffer.Length);
                                aZipStream.Write(buffer, 0, sizeRead);
                            }
                            while (sizeRead > 0);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                        aStreamToZip.Close();
                    }
                    aZipStream.Finish();
                    aZipStream.Close();
                }
                aZipFile.Close();
            }
            return sZipFileName;
        }