您的位置:首页 > 编程学习 > C# > 正文

C# 文件压缩与解压

更多 时间:2016-5-8 类别:编程学习 浏览量:1070

C# 文件压缩与解压

C# 文件压缩与解压

一、准备工作

 

1、下载 ICSharpCode.SharpZipLib.dll 文件

2、项目中引用这个dll

 

 

二、文件压缩与解压共用类

 

  •  
  • C# 代码   复制
  • 
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using ICSharpCode.SharpZipLib.Checksums;
    using ICSharpCode.SharpZipLib.Zip;
    
    namespace ZIPUtilities
    {
         /// <summary>
         /// Zip压缩帮助类
        /// </summary>
        public class ZipHelper
        {
            /// <summary>
            /// 压缩文件夹
            /// </summary>
            /// <param name="dirToZip"></param>
            /// <param name="zipedFileName"></param>
            /// <param name="compressionLevel">压缩率0(无压缩)9(压缩率最高)</param>
            public void ZipDir(string dirToZip, string zipedFileName, int compressionLevel = 9)
            {
                if (Path.GetExtension(zipedFileName) != ".zip")
                {
                    zipedFileName = zipedFileName + ".zip";
                }
                using (var zipoutputstream = new ZipOutputStream(File.Create(zipedFileName)))
                {
                    zipoutputstream.SetLevel(compressionLevel);
                    Crc32 crc = new Crc32();
                    Hashtable fileList = GetAllFies(dirToZip);
                    foreach (DictionaryEntry item in fileList)
                    {
                        FileStream fs = new FileStream(item.Key.ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        // ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(dirToZip.Length + 1));
                        ZipEntry entry = new ZipEntry(Path.GetFileName(item.Key.ToString()))
                                         {
                                             DateTime = (DateTime) item.Value,
                                             Size = fs.Length
                                         };
                        fs.Close();
                        crc.Reset();
                        crc.Update(buffer);
                        entry.Crc = crc.Value;
                        zipoutputstream.PutNextEntry(entry);
                        zipoutputstream.Write(buffer, 0, buffer.Length);
                    }
                }
            }
    
            /// <summary>  
            /// 获取所有文件  
            /// </summary>  
            /// <returns></returns>  
            public Hashtable GetAllFies(string dir)
            {
                Hashtable filesList = new Hashtable();
                DirectoryInfo fileDire = new DirectoryInfo(dir);
                if (!fileDire.Exists)
                {
                    throw new FileNotFoundException("目录:" + fileDire.FullName + "没有找到!");
                }
    
                GetAllDirFiles(fileDire, filesList);
                GetAllDirsFiles(fileDire.GetDirectories(), filesList);
                return filesList;
            }
    
            /// <summary>  
            /// 获取一个文件夹下的所有文件夹里的文件  
            /// </summary>  
            /// <param name="dirs"></param>  
            /// <param name="filesList"></param>  
            public void GetAllDirsFiles(IEnumerable<DirectoryInfo> dirs, Hashtable filesList)
            {
                foreach (DirectoryInfo dir in dirs)
                {
                    foreach (FileInfo file in dir.GetFiles("*.*"))
                    {
                        filesList.Add(file.FullName, file.LastWriteTime);
                    }
                    GetAllDirsFiles(dir.GetDirectories(), filesList);
                }
            }
    
            /// <summary>  
            /// 获取一个文件夹下的文件  
            /// </summary>  
            /// <param name="dir">目录名称</param>
            /// <param name="filesList">文件列表HastTable</param>  
            public static void GetAllDirFiles(DirectoryInfo dir, Hashtable filesList)
            {
                foreach (FileInfo file in dir.GetFiles("*.*"))
                {
                    filesList.Add(file.FullName, file.LastWriteTime);
                }
            }
    
            /// <summary>  
            /// 功能:解压zip格式的文件。  
            /// </summary>  
            /// <param name="zipFilePath">压缩文件路径</param>  
            /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>  
            /// <returns>解压是否成功</returns>  
            public void UnZip(string zipFilePath, string unZipDir)
            {
                if (zipFilePath == string.Empty)
                {
                    throw new Exception("压缩文件不能为空!");
                }
                if (!File.Exists(zipFilePath))
                {
                    throw new FileNotFoundException("压缩文件不存在!");
                }
                //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹  
                if (unZipDir == string.Empty)
                    unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
                if (!unZipDir.EndsWith("/"))
                    unZipDir += "/";
                if (!Directory.Exists(unZipDir))
                    Directory.CreateDirectory(unZipDir);
    
                using (var s = new ZipInputStream(File.OpenRead(zipFilePath)))
                {
    
                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName = Path.GetFileName(theEntry.Name);
                        if (!string.IsNullOrEmpty(directoryName))
                        {
                            Directory.CreateDirectory(unZipDir + directoryName);
                        }
                        if (directoryName != null && !directoryName.EndsWith("/"))
                        {
                        }
                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
                            {
    
                                int size;
                                byte[] data = new byte[2048];
    

    标签:C#