C#生成ZIP压缩包

2018-06-18 03:45:08来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

生成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

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:MVC Razor 一些常用的方法

下一篇:RadioButton 和 RadioButtonList 比较