C#使用SharpZipLib压缩单个文件

版权声明:本文为博主原创文章,不需博主允许即可随意转载。 https://blog.csdn.net/a_dev/article/details/82315811

引入:

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;
        }

猜你喜欢

转载自blog.csdn.net/a_dev/article/details/82315811
今日推荐