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

 

转载于:https://www.cnblogs.com/xuezhizhang/p/3422946.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值