zoukankan      html  css  js  c++  java
  • 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("异常描述:	" + ex.Message);
                    logger.Error("异常方法:	" + ex.TargetSite);
                    logger.Error("异常堆栈:	" + 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("异常描述:	" + ex.Message);
                    logger.Error("异常方法:	" + ex.TargetSite);
                    logger.Error("异常堆栈:	" + 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

  • 相关阅读:
    2021 RoboCom 世界机器人开发者大赛-本科组(初赛)7-1 懂的都懂 (20 分)
    PTA 乙级 1080 MOOC期终成绩 (25 分) C++
    PTA 乙级 1079 延迟的回文数 (20 分) C++
    PTA 乙级 1078 字符串压缩与解压 (20 分) C++
    PTA 乙级 1077 互评成绩计算 (20 分) C++
    PTA 乙级 1076 Wifi密码 (15 分) python
    PTA 乙级 1075 链表元素分类 (25 分) C++
    Hadoop 代码实现文件上传
    Django学习笔记十---FBV视图--003篇---获取请求信息
    Django学习笔记十---FBV视图--002篇---设置重定向和异常响应
  • 原文地址:https://www.cnblogs.com/xuezhizhang/p/3422946.html
Copyright © 2011-2022 走看看