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:https://files.cnblogs.com/xuezhizhang/ICSharpCode.SharpZipLib.zip

 

posted @ 2013-11-14 11:32  志在必得Shaun  阅读(4006)  评论(0编辑  收藏  举报