C#压缩文件夹坑~

dotNet疯狂之路No.29

 今天很残酷,明天更残酷,后天很美好,但是绝大部分人是死在明天晚上,只有那些真正的英雄才能见到后天的太阳。

 We're here to put a dent in the universe. Otherwise why else even be here?  

C#压缩文件夹坑~    

开始从网上找了个压缩的示例  我去坑的不要不要的 没办法重新找 都是复制来复制去 没啥意思

前提:ICSharpCode.SharpZipLib.dll引用

创建一个类

public class ZipClass
{
    /// <summary>
    /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略)
    /// </summary>
    /// <param name="dirPath">被压缩的文件夹夹路径</param>
    /// <param name="zipFilePath">生成压缩文件的路径</param> 
    /// <returns>是否压缩成功</returns>
    public static bool ZipFiles(string dirPath, string zipFilePath )
    {
      
        
       

        try
        {
            string[] filenames = Directory.GetFiles(dirPath);
            using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
            {
                s.SetLevel(9);//0-9 值越大压缩率越高
                byte[] buffer = new byte[4096];
                foreach (string file in filenames)
                {
                    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);
                    }
                }
                s.Finish();
                s.Close();
            }
        }
        catch (Exception ex)
        {
           
            return false;
        }
        return true;
    }
     
}

  

 

原文地址:https://www.cnblogs.com/moxuanshang/p/7274046.html