基于C#实现压缩和解压文件及文件夹

 更新时间:2024年03月12日 11:09:52   作者:无熵~  
这篇文章主要为大家详细介绍了基于C#实现压缩和解压文件及文件夹的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

C#压缩和解压文件及文件夹有以下几种方式:

ZipFile(.NET 4.5 System.IO.Compression命名空间中新提供的压缩类)

ZipArchive

SharpZipLib和DotNetZip 

使用第三方压缩软件

使用ZipFile

引用.NET 4.5程序集:System.IO.Compression 和 System.IO.Compression.FileSystem.

    public class CompressionHelper
    {
        /// <summary>
        /// 将指定目录压缩为Zip文件
        /// </summary>
        /// <param name="folderPath">文件夹地址 D:/1/ </param>
        /// <param name="zipPath">zip地址 D:/1.zip </param>
        public static void CompressDirectoryZip(string folderPath, string zipPath)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(zipPath);
 
            if (directoryInfo.Parent != null)
            {
                directoryInfo = directoryInfo.Parent;
            }
 
            if (!directoryInfo.Exists)
            {
                directoryInfo.Create();
            }
 
            System.IO.Compression.ZipFile.CreateFromDirectory(folderPath, zipPath, CompressionLevel.Optimal, false);
        }
 
        /// <summary>
        /// 将指定文件压缩为Zip文件
        /// </summary>
        /// <param name="filePath">文件地址 D:/1.txt </param>
        /// <param name="zipPath">zip地址 D:/1.zip </param>
        public static void CompressFileZip(string filePath, string zipPath)
        {
 
            FileInfo fileInfo = new FileInfo(filePath);
            string dirPath = fileInfo.DirectoryName?.Replace("\\", "/") + "/";
            string tempPath = dirPath + Guid.NewGuid() + "_temp/";
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            fileInfo.CopyTo(tempPath + fileInfo.Name);
            CompressDirectoryZip(tempPath, zipPath);
            DirectoryInfo directory = new DirectoryInfo(tempPath);
            if (directory.Exists)
            {
                //将文件夹属性设置为普通,如:只读文件夹设置为普通
                directory.Attributes = FileAttributes.Normal;
 
                directory.Delete(true);
            }
        }
 
 
        /// <summary>
        /// 解压Zip文件到指定目录
        /// </summary>
        /// <param name="zipPath">zip地址 D:/1.zip</param>
        /// <param name="folderPath">文件夹地址 D:/1/</param>
        public static void DecompressZip(string zipPath, string folderPath)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
 
            if (!directoryInfo.Exists)
            {
                directoryInfo.Create();
            }
 
            System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, folderPath);
        }
 
    }

使用ZipArchive

    public class ZipArchiveHelper
    {
        public static void ZipFile(string sourceFilePath, string zipFilePath)
        {
            System.IO.Compression.ZipFile.CreateFromDirectory(sourceFilePath, zipFilePath);
 
            // 创建并添加被压缩文件
            using (FileStream zipFileToOpen = new FileStream(sourceFilePath, FileMode.Create))
            {
                using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Create))
                {
                    string filename = System.IO.Path.GetFileName(zipFilePath);
                    ZipArchiveEntry readMeEntry = archive.CreateEntry(filename);
                    using (System.IO.Stream stream = readMeEntry.Open())
                    {
                        byte[] bytes = System.IO.File.ReadAllBytes(zipFilePath);
                        stream.Write(bytes, 0, bytes.Length);
                    }
                }
            }
        }
 
        /// <summary>
        /// 在压缩文件中添加文件
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="zipFilePath"></param>
        public static void AddZipFile(string sourceFilePath, string zipFilePath)
        {
            using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Create))
            {
                using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Create))
                {
                    string filename = System.IO.Path.GetFileName(sourceFilePath);
                    ZipArchiveEntry readMeEntry = archive.CreateEntry(filename);
                    using (System.IO.Stream stream = readMeEntry.Open())
                    {
                        byte[] bytes = System.IO.File.ReadAllBytes(sourceFilePath);
                        stream.Write(bytes, 0, bytes.Length);
                    }
                }
            }
 
        }
 
        /// <summary>
        /// 解压压缩文件
        /// </summary>
        /// <param name="zipFilePath"></param>
        /// <param name="unzipFilePath"></param>
        public static void UzipFile(string zipFilePath, string unzipFilePath)
        {
            using (FileStream instream = File.OpenRead(zipFilePath))
            {
                using (ZipArchive zip = new ZipArchive(instream))
                {
 
                    foreach (ZipArchiveEntry et in zip.Entries)
                    {
                        using (Stream stream = et.Open())
                        {
                            using (FileStream fsout = File.Create(System.IO.Path.Combine(unzipFilePath, et.Name)))
                            {
                                stream.CopyTo(fsout);
                            }
                        }
                    }
                }
            }
        }
    }

使用SharpZipLib

    public class SharpZipLib
    {
        /// <summary>
        /// 压缩文件夹
        /// </summary>
        /// <param name="dirPath">文件夹路径</param>
        /// <param name="password">压缩包设置密码(注:可为空)</param>
        /// <param name="zipFilePath">压缩包路径+名称+后缀(注:可为空,默认同目录)</param>
        /// <returns></returns>
        public string ZipFiles(string dirPath, string password, string zipFilePath)
        {
            if (zipFilePath == string.Empty)
            {
                //压缩文件名为空时使用文件夹名+.zip
                zipFilePath = GetZipFilePath(dirPath);
            }
            try
            {
                string[] filenames = Directory.GetFiles(dirPath);
                using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
                {
                    s.SetLevel(9);
                    s.Password = password;
                    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();
                }
                return zipFilePath;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
 
        /// <summary>
        /// 减压文件夹
        /// </summary>
        /// <param name="zipFilePath">压缩包地址+名称+后缀</param>
        /// <param name="password">密码(注:可为空)</param>
        /// <param name="unZippath">减压后保存的路径(注:可为空,默认同目录)</param>
        /// <returns></returns>
        public string UnZips(string zipFilePath, string password, string unZippath)
        {
            try
            {
                if (unZippath == string.Empty)
                {
                    //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
                    unZippath = GetUnZipFilePath(zipFilePath);
                }
                if (CreatePath(unZippath) && IsExistFilePath(zipFilePath))
                {
                    string directoryName = Path.GetDirectoryName(unZippath);
                    {
                        using (ZipInputStream zipInStream = new ZipInputStream(File.OpenRead(zipFilePath)))
                        {
                            zipInStream.Password = password;
                            ZipEntry entry = zipInStream.GetNextEntry();
                            do
                            {
                                using (FileStream fileStreamOut = File.Create(directoryName + "\\" + entry.Name))
                                {
                                    int size = 2048;
                                    byte[] buffer = new byte[size];
                                    do
                                    {
                                        size = zipInStream.Read(buffer, 0, buffer.Length);
                                        fileStreamOut.Write(buffer, 0, size);
                                    } while (size > 0);
                                    fileStreamOut.Close();
                                    fileStreamOut.Dispose();
                                }
                            } while ((entry = zipInStream.GetNextEntry()) != null);
                            zipInStream.Close();
                            zipInStream.Dispose();
                            return unZippath;
                        }
                    }
                }
                return "请确认压缩包文件地址与解压后保存地址是否可以访问!";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
 
        /// <summary>  
        /// 压缩文件  
        /// </summary>  
        /// <param name="dirFilePath">文件路径+名称+后缀</param>
        /// <param name="password">压缩包设置密码(注:可为空)</param>
        /// <param name="zipFilePath">压缩包路径+名称+后缀(注:可为空,默认同目录)</param>
        public string ZipFile(string dirFilePath, string password, string zipFilePath)
        {
            try
            {
                if (IsExistFilePath(dirFilePath))
                {
                    if (zipFilePath == string.Empty)
                    {
                        zipFilePath = GetZipFilePath(dirFilePath.Replace(Path.GetExtension(dirFilePath), ""));
                    }
                    string filename = Path.GetFileName(dirFilePath);
                    FileStream streamToZip = new FileStream(dirFilePath, FileMode.Open, FileAccess.Read);
                    FileStream zipFile = File.Create(zipFilePath);
                    using (ZipOutputStream zipStream = new ZipOutputStream(zipFile))
                    {
                        ZipEntry zipEntry = new ZipEntry(filename);
                        zipStream.PutNextEntry(zipEntry);
                        zipStream.SetLevel(9);
                        zipStream.Password = password;
                        byte[] buffer = new byte[2048];
                        System.Int32 size = streamToZip.Read(buffer, 0, buffer.Length);
                        zipStream.Write(buffer, 0, size);
                        while (size < streamToZip.Length)
                        {
                            int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
                            zipStream.Write(buffer, 0, sizeRead);
                            size += sizeRead;
                        }
                        zipStream.Finish();
                        zipStream.Close();
                        streamToZip.Close();
                    }
                    return zipFilePath;
                }
                return "请确认压缩包文件地址与解压后保存地址是否可以访问!";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
 
        /// <summary>
        /// 创建路径
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public bool CreatePath(string path)
        {
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                    return true;
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
 
        /// <summary>
        /// 文件是否存在
        /// </summary>
        /// <param name="filePath">路劲+名称+后缀</param>
        /// <returns></returns>
        public bool IsExistFilePath(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return false;
            }
            return true;
        }
 
        /// <summary>
        /// 获取默认压缩路径+文件名+后缀【.zip】
        /// </summary>
        /// <param name="path">需要压缩的文件夹路径(注:不包含.后缀)</param>
        /// <returns>与压缩文件同一目录路径</returns>
        public string GetZipFilePath(string path)
        {
            if (path.EndsWith("\\"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            return path + ".zip";
        }
 
        /// <summary>
        ///  获取默认解压路径
        /// </summary>
        /// <param name="path">需要解压的压缩包文件地址</param>
        /// <returns>与解压文件同一目录路径</returns>
        public string GetUnZipFilePath(string path)
        {
            path = path.Replace(Path.GetFileName(path), Path.GetFileNameWithoutExtension(path));
            if (!path.EndsWith("/"))
            {
                path += "/";
            }
            return path;
        }
 
        /// <summary>
        /// 获取路径中所有文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        private Hashtable getAllFies(string path)
        {
            Hashtable FilesList = new Hashtable();
            DirectoryInfo fileDire = new DirectoryInfo(path);
            if (fileDire.Exists)
            {
                this.getAllDirFiles(fileDire, FilesList);
                this.getAllDirsFiles(fileDire.GetDirectories(), FilesList);
            }
            this.getAllDirFiles(fileDire, FilesList);
            this.getAllDirsFiles(fileDire.GetDirectories(), FilesList);
            return FilesList;
        }
 
        /// <summary>  
        /// 获取一个文件夹下的所有文件夹里的文件  
        /// </summary>  
        /// <param name="dirs"></param>  
        /// <param name="filesList"></param>  
        private void getAllDirsFiles(DirectoryInfo[] dirs, Hashtable filesList)
        {
            foreach (DirectoryInfo dir in dirs)
            {
                foreach (FileInfo file in dir.GetFiles("*.*"))
                {
                    filesList.Add(file.FullName, file.LastWriteTime);
                }
                this.getAllDirsFiles(dir.GetDirectories(), filesList);
            }
        }
 
        /// <summary>  
        /// 获取一个文件夹下的文件  
        /// </summary>  
        /// <param name="strDirName">目录名称</param>  
        /// <param name="filesList">文件列表HastTable</param>  
        private void getAllDirFiles(DirectoryInfo dir, Hashtable filesList)
        {
            foreach (FileInfo file in dir.GetFiles("*.*"))
            {
                filesList.Add(file.FullName, file.LastWriteTime);
            }
        }
    }

使用第三方压缩软件

    public  class WinrarZip
    {
        public static bool Zip(string strzipPath, string strtxtPath, string password)
        {
            try
            {
                System.Diagnostics.Process Process1 = new System.Diagnostics.Process();
                Process1.StartInfo.FileName = "Winrar.exe";
                Process1.StartInfo.CreateNoWindow = true;
                Process1.StartInfo.Arguments = " a -p" + password + " " + strzipPath + " " + strtxtPath;
                //strtxtPath = "c://freezip//";
                //Process1.StartInfo.Arguments = " x -p123456 " + strzipPath + " " + strtxtPath;
                Process1.Start();
                if (Process1.HasExited)
                {
                    return true;
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
 
        }
 
        public static bool UZip(string strzipPath, string strtxtPath, string password)
        {
            try
            {
                System.Diagnostics.Process Process1 = new System.Diagnostics.Process();
                Process1.StartInfo.FileName = "Winrar.exe";
                Process1.StartInfo.CreateNoWindow = true;
                //Process1.StartInfo.Arguments = " a -p123456 " + strzipPath + " " + strtxtPath;
                //strtxtPath = "c://freezip//";
                Process1.StartInfo.Arguments = " x -p" + password + " " + strzipPath + " " + strtxtPath;
                Process1.Start();
                if (Process1.HasExited)
                {
                    return true;
                }
                return true;
            }
            catch (Exception)
            {
 
                return false;
            }
 
        }
    }

到此这篇关于基于C#实现压缩和解压文件及文件夹的文章就介绍到这了,更多相关C#压缩和解压文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • C#实现简单的计算器小功能

    C#实现简单的计算器小功能

    这篇文章主要为大家详细介绍了C#实现简单的计算器小功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • Unity实现跑马灯效果的示例代码

    Unity实现跑马灯效果的示例代码

    这篇文章主要为大家详细介绍了如何利用Unity实现跑马灯效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-05-05
  • 浅拷贝和深拷贝深入理解(shallow copy VS deep copy)

    浅拷贝和深拷贝深入理解(shallow copy VS deep copy)

    浅拷贝和深拷贝深入理解(shallow copy VS deep copy) 本文重点讨论引用类型变量的拷贝机制和实现
    2014-01-01
  • 轻松学习C#的属性

    轻松学习C#的属性

    轻松学习C#的属性,对C#的属性感兴趣的朋友可以参考本篇文章,帮助大家更灵活的运用C#的属性
    2015-11-11
  • C#实现Excel数据导入到SQL server数据库

    C#实现Excel数据导入到SQL server数据库

    这篇文章主要为大家详细介绍了在C#中如何实现Excel数据导入到SQL server数据库中,文中的示例代码简洁易懂,希望对大家有一定的帮助
    2024-03-03
  • C#延时关闭电脑、取消关闭电脑操作方法(需管理员权限)

    C#延时关闭电脑、取消关闭电脑操作方法(需管理员权限)

    在C#中,如果想实现延时关闭电脑和取消关闭的功能,可以有多种方法,下面给大家分享C#延时关闭电脑、取消关闭电脑操作方法,感兴趣的朋友一起看看吧
    2024-06-06
  • C#中Lambda表达式的用法

    C#中Lambda表达式的用法

    这篇文章介绍了C#中Lambda表达式的用法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-04-04
  • C#中的DataTable查询实战教程

    C#中的DataTable查询实战教程

    这篇文章主要介绍了C#中的DataTable查询实战教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-01-01
  • 验证码的三个常见漏洞和修复方法

    验证码的三个常见漏洞和修复方法

    这篇文章主要介绍了验证码的三个常见漏洞和修复方法,本文讲解了把验证码存储在Cookie中、没有进行非空判断、没有及时销毁验证码三个常见问题和解决方法,需要的朋友可以参考下
    2015-03-03
  • C#使用Redis的基本操作

    C#使用Redis的基本操作

    这篇文章主要介绍了C#使用Redis的基本操作,需要的朋友可以参考下
    2017-06-06

最新评论