C# 压缩与解压操作

依赖:.NET Framework 4.5及以上,引用 - 添加引用 - 程序集
System.IO.Compression
System.IO.Compression.FileSystem

 

针对文件夹的最简单的压缩与解压缩
1、目录必须存在
2、无法覆盖文件

 

public static void DoZipFile(List<string> AllFiles, string FileDir, string OutputDir)
        {
            if (!Regex.IsMatch(FileDir, @".*[/\\]$"))
            {
                FileDir += "\\";
            }
 
            using (FileStream fs = new FileStream(OutputDir, FileMode.Create))
            {
                using (ZipArchive ar = new ZipArchive(fs, ZipArchiveMode.Create))
                {
                    foreach (string file in AllFiles)
                    {
                        FileInfo info = new FileInfo(file);
                        if(!new DirectoryInfo(FileDir).FullName.StartsWith(info.Directory.FullName))
                        {
                            throw new Exception("Compress file must exist in the specific directory");
                        }
 
                        ar.CreateEntryFromFile(info.FullName, info.FullName.Substring(FileDir.Length));
                    }
                }
            }
        }
 
        public static void UnZipFile(string ZipFile, string OutputPath)
        {
            if (!Regex.IsMatch(OutputPath, @".*[/\\]$"))
            {
                OutputPath += "\\";
            }
 
            using (FileStream fs = new FileStream(ZipFile, FileMode.Open))
            {
                using (ZipArchive zr = new ZipArchive(fs))
                {
                    foreach (var en in zr.Entries)
                    {
                        FileInfo path = new FileInfo(OutputPath + en.FullName);
                         
                        if(!path.Directory.Exists)
                        {
                            path.Directory.Create();
                        }
 
                        if(en.Name == "") //是文件夹
                        {
                            Directory.CreateDirectory(OutputPath + en.FullName);
                        }
                        else
                        {
                            en.ExtractToFile(OutputPath + en.FullName, true);
                        }
                    }
                }
            }
 
        }

  

 

带判断剩余空间够不够的代码

复制代码
 public static void DoZipFile(List<string> AllFiles, string FileDir, string OutputDir)
        {
            if (!Regex.IsMatch(FileDir, @".*[/\\]$"))
            {
                FileDir += "\\";
            }

                      
            using (MemoryStream memoryStream = new MemoryStream())
            {
                ZipArchive ar = new ZipArchive(memoryStream, ZipArchiveMode.Create);

                foreach (string file in AllFiles)
                {
                    FileInfo info = new FileInfo(file);
                    if(!new DirectoryInfo(FileDir).FullName.StartsWith(info.Directory.FullName))
                    {
                        throw new Exception("Compress file must exist in the specific directory");
                    }

                    ar.CreateEntryFromFile(info.FullName, info.FullName.Substring(FileDir.Length));
                }

                byte[] bytesCompress = memoryStream.ToArray();
                long sizeCompressFile = bytesCompress.Length;

                //判断磁盘存储空间是否可以容纳生成的文件          
                string filePathRoot = Path.GetPathRoot(OutputDir);
                if (!filePathRoot.EndsWith("\\"))
                {
                    filePathRoot = filePathRoot + "\\";
                }

                DriveType driveType = (DriveType)GetDriveType(filePathRoot);

                if (driveType == DriveType.FixedDisk || driveType == DriveType.FloppyOrUsb)  //本地磁盘驱动器或usb、软盘
                {
                    long diskFreeSpace = GetHardDiskFreeSpace(filePathRoot);
                    if (sizeCompressFile <= diskFreeSpace)
                    {
                        FileStream fsWrite = File.OpenWrite(OutputDir);
                        fsWrite.Write(bytesCompress, 0, bytesCompress.Length);
                        fsWrite.Close();
                    }
                    else
                    {
                        
                    }
                }
                else if (driveType == DriveType.NetDisk) //网络共享文件夹所在磁盘大小   
                {
                    long freeSpaceNetFolder = 0, dummy1 = 0, dummy2 = 0;

                    GetDiskFreeSpaceEx(filePathRoot, ref freeSpaceNetFolder, ref dummy1, ref dummy2);

                    if (sizeCompressFile <= freeSpaceNetFolder)
                    {
                        FileStream fsWrite = File.OpenWrite(OutputDir);
                        fsWrite.Write(bytesCompress, 0, bytesCompress.Length);
                        fsWrite.Close();
                    }
                    else
                    {
                       
                    }
                }
            }
        }
复制代码
复制代码
public static void UnZipFile(string ZipFile, string OutputPath)
        {
            if (!Regex.IsMatch(OutputPath, @".*[/\\]$"))
            {
                OutputPath += "\\";
            }

            using (FileStream fs = new FileStream(ZipFile, FileMode.Open))
            {
                using (ZipArchive zr = new ZipArchive(fs))
                {
                    long sizeDeCompressFile = 0;

                    for(int i = 0; i < zr.Entries.Count; i++)
                    {
                        sizeDeCompressFile += zr.Entries[i].Length;
                    }

                    //判断磁盘存储空间是否可以容纳生成的文件          
                    string filePathRoot = Path.GetPathRoot(OutputPath);
                    if (!filePathRoot.EndsWith("\\"))
                    {
                        filePathRoot = filePathRoot + "\\";
                    }

                    DriveType driveType = (DriveType)GetDriveType(filePathRoot);

                    if (driveType == DriveType.FixedDisk || driveType == DriveType.FloppyOrUsb)  //本地磁盘驱动器或usb、软盘
                    {
                        long diskFreeSpace = GetHardDiskFreeSpace(filePathRoot);
                        if (sizeDeCompressFile > diskFreeSpace)
                        {
                            return;
                        }
                    }
                    else if (driveType == DriveType.NetDisk) //网络共享文件夹所在磁盘大小   
                    {
                        long freeSpaceNetFolder = 0, dummy1 = 0, dummy2 = 0;

                        GetDiskFreeSpaceEx(filePathRoot, ref freeSpaceNetFolder, ref dummy1, ref dummy2);

                        if (sizeDeCompressFile > freeSpaceNetFolder)
                        {
                            return;
                        }
                    }

                    foreach (var en in zr.Entries)
                    {
                        FileInfo path = new FileInfo(OutputPath + en.FullName);
                        
                        if(!path.Directory.Exists)
                        {
                            path.Directory.Create();
                        }

                        if(en.Name == "") //是文件夹
                        {
                            Directory.CreateDirectory(OutputPath + en.FullName);
                        }
                        else
                        {
                            en.ExtractToFile(OutputPath + en.FullName, true);
                        }
                    }
                }
            }

        }
复制代码

如果以上有函数找不到,请参考我的另外一个随笔 C# 获取本地磁盘驱动器、U盘、共享目录所在驱动器的大小 - wu.g.q - 博客园 (cnblogs.com)

posted on   wu.g.q  阅读(154)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
历史上的今天:
2021-04-03 WPF奇怪问题总结
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示