C#生成ZIP壓縮包


生成ZIP壓縮包C#代碼如下:

using System;
using System.Collections.Generic;
using System.Text;

using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
using log4net;
using log4net.Config;

namespace Test.BLL
{
    public class TestZipFile
    {
        protected static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        ///<summary>
        /// 創建ZIP文件
        ///</summary>
        public void CreateZipFile(string[] files, string sTempFile, string sPassWord)
        {
            try
            {
                using (ZipOutputStream s = new ZipOutputStream(File.Create(sTempFile)))
                {
                    s.SetLevel(9); // 壓縮級別 0-9
                    if (sPassWord != "")
                    {
                        s.Password = sPassWord; //Zip壓縮文件密碼
                    }

                    byte[] buffer = new byte[4096]; //緩沖區大小

                    foreach (string file in files)
                    {
                        if (!string.IsNullOrEmpty(file))
                        {
                            if (File.Exists(file))
                            {
                                ZipEntry entry = new ZipEntry(Path.GetFileName(file));
                                entry.DateTime = DateTime.Now;
                                s.PutNextEntry(entry);

                                using (FileStream fs = File.OpenRead(file))
                                {
                                    int sourceBytes;
                                    do
                                    {
                                        sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                        s.Write(buffer, 0, sourceBytes);
                                    } while (sourceBytes > 0);
                                }
                            }
                            else
                            {
                                logger.Error("文件:" + file + "不存在。");
                            }
                        }
                    }

                    s.Finish();
                    s.Close();
                }
            }
            catch (Exception ex)
            {
                logger.Error("壓縮文件時異常!");
                logger.Error("異常描述:\t" + ex.Message);
                logger.Error("異常方法:\t" + ex.TargetSite);
                logger.Error("異常堆棧:\t" + ex.StackTrace);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="files">放入ZIP的文件路勁(含文件名)</param>
        /// <param name="sTempFile">創建的ZIP文件路勁(含文件名)</param>
        /// <param name="sPassWord">ZIP文件密碼</param>
        /// <param name="folderNames">存放到ZIP中的文件夾名,空代表放在頂級目錄</param>
        public void CreateZipFileMutilFolder(string[] files, string sTempFile, string sPassWord, string[] folderNames)
        {
            try
            {
                using (ZipOutputStream s = new ZipOutputStream(File.Create(sTempFile)))
                {
                    s.SetLevel(9); // 壓縮級別 0-9
                    if (sPassWord != "")
                    {
                        s.Password = sPassWord; //Zip壓縮文件密碼
                    }

                    byte[] buffer = new byte[4096]; //緩沖區大小

                    int i = 0;
                    foreach (string file in files)
                    {
                        if (!string.IsNullOrEmpty(file))
                        {
                            if (File.Exists(file))
                            {
                                ZipEntry entry = new ZipEntry((string.IsNullOrEmpty(folderNames[i]) ? "" : (folderNames[i] + "\\")) + Path.GetFileName(file));
                                entry.DateTime = DateTime.Now;
                                s.PutNextEntry(entry);

                                using (FileStream fs = File.OpenRead(file))
                                {
                                    int sourceBytes;
                                    do
                                    {
                                        sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                        s.Write(buffer, 0, sourceBytes);
                                    } while (sourceBytes > 0);
                                }
                            }
                            else
                            {
                                logger.Error("文件:" + file + "不存在。");
                            }
                        }

                        i++;
                    }

                    s.Finish();
                    s.Close();
                }
            }
            catch (Exception ex)
            {
                logger.Error("壓縮文件時異常!");
                logger.Error("異常描述:\t" + ex.Message);
                logger.Error("異常方法:\t" + ex.TargetSite);
                logger.Error("異常堆棧:\t" + ex.StackTrace);
            }
        }
    }
}

其中會用到的文件名、文件路徑非法字符替換方法:

        /// <summary>  
        /// Remove invalid characters which are not allowed in the file name  
        /// </summary>  
        /// <param name="fileName"></param>  
        /// <returns></returns>  
        public string RemoveFileNameInvalidChar(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))

                return fileName;

            string invalidChars = new string(Path.GetInvalidFileNameChars());

            string invalidReStr = string.Format("[{0}]", Regex.Escape(invalidChars));

            return Regex.Replace(fileName, invalidReStr, "");

        }

        /// <summary>  
        /// Remove invalid characters which are not allowed in the path names  
        /// </summary>  
        /// <param name="filePath"></param>  
        /// <returns></returns>  
        public string RemovePathInvalidChar(string filePath)
        {

            if (string.IsNullOrEmpty(filePath))

                return filePath;

            string invalidChars = new string(Path.GetInvalidPathChars());

            string invalidReStr = string.Format("[{0}]", Regex.Escape(invalidChars));

            return Regex.Replace(filePath, invalidReStr, "");

        }

參考:http://jianyun.org/archives/959.html

ZIP DLL:http://files.cnblogs.com/xuezhizhang/ICSharpCode.SharpZipLib.zip

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM