C#压缩和解压文件

这里用两种方法实现C#压缩和解压文件

1、使用System.IO.Compression名称空间下的相关类(需引用 System.IO.Compression.FileSystem和System.IO.Compression程序集)

 创建zip压缩文件

使用ZipFile类CreateFromDirectory()方法来创建zip压缩文件。它有3种重载形式,这里说一下常用的两个

 public static void CreateFromDirectory(
    string sourceDirectoryName,
    string destinationArchiveFileName
 )

public static void CreateFromDirectory(
     string sourceDirectoryName,//sourceDirectoryName 要压缩的文件夹
     string destinationArchiveFileName, //destinationArchiveFileName 压缩后的文件名
     CompressionLevel compressionLevel,//compressionLevel 压缩级别  Fastest-最快 NoCompression-不压缩 Optimal-最好
     bool includeBaseDirectory //includeBaseDirectory 是否包含当前目录
 )

测试代码如下:

1 static void Main(string[] args)
2         {
3             ZipFile.CreateFromDirectory("D:\test", "D:\a.zip");
4         }

在D盘创建一个test目录,里面放一张图片,

运行

结果如下:

1   static void Main(string[] args)
2         {           
3             ZipFile.CreateFromDirectory("D:\test", "D:\b.zip",CompressionLevel.Optimal,true);
4         }

运行结果如下

解压zip压缩文件

使用 ZipFile类的ExtractToDirectory()方法

1 public static void ExtractToDirectory(
2     string sourceArchiveFileName,  //压缩文件完整路径
3     string destinationDirectoryName //指定解压文件夹
4 )
1  static void Main(string[] args)
2         {          
3             ZipFile.ExtractToDirectory("D:\a.zip", "D:\");
4         }

运行结果如下

这里需要注意的是,如果文件已存在,会引发一个IOException

添加文件到现有zip压缩文件

1 using (FileStream fs = new FileStream("D:\a.zip", FileMode.Open))
2             {
3                 using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Update))
4                 {
5                     archive.CreateEntryFromFile("C:\Users\ZhaoJia\Pictures\1.jpg","1.jpg");                                      
6                 }
7             }

运行结果如下

创建gz压缩文件

使用GZipStream类来创建gz压缩文件

 1  static void Main(string[] args)
 2         {
 3             string filePath = "D:\test";    //要添加到压缩文件的目录
 4             string targetPath = "D:\";      //压缩文件存放的目录         
 5 
 6             DirectoryInfo dirInfo = new DirectoryInfo(filePath);
 7 
 8             foreach (FileInfo fileInfo in dirInfo.GetFiles())
 9             {
10                 using (FileStream fsorg = fileInfo.OpenRead())
11                 {
12                     using (FileStream fs = File.Create(targetPath + fileInfo.Name + ".gz"))
13                     {
14                         using (GZipStream compressionStream = new GZipStream(fs,
15                             CompressionMode.Compress))
16                         {
17                             fsorg.CopyTo(compressionStream);
18                         }
19                     }
20                 }
21             }
22         }

使用这个类来创建gz文件有几个缺陷

1、压缩文件里只能有一个文件

2、压缩后的文件名要带上压缩文件里文件的后缀名。如有一个图像文件为a.jpg,生成的gz压缩文件名为  a.jpg.gz

解压gz压缩文件

 1   string compressFilePath = "D:\4172212144245982608.jpg.gz";//压缩文件名
 2 
 3             FileInfo fileInfo = new FileInfo(compressFilePath);
 4 
 5             using (FileStream originalFileStream = fileInfo.OpenRead())
 6             {
 7                 string currentFileName = fileInfo.FullName;
 8                 string newFileName = currentFileName.Remove(currentFileName.Length - fileInfo.Extension.Length);
 9 
10                 using (FileStream decompressedFileStream = File.Create(newFileName))
11                 {
12                     using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
13                     {
14                         decompressionStream.CopyTo(decompressedFileStream);                   
15                     }
16                 }
17             }

2、使用WinRAR

WinRAR提供了一个控制台版本的exe,我们可以调用这个exe来压缩和解压文件

WinRAR支持的格式比较多,包括RAR、7Z、ACE、ARJ、BZ2、CAB、GZ、ISO、JAR、LZH、TAR、UUE、XZ、Z、001

这个exe不依赖其它的库,这里我们直接拷到项目的运行目录下

Rar.exe支持的命令参数非常多,这里不全部介绍。有兴趣的可以运行Rar -?查看详细的命令说明

1、创建rar压缩文件

语法如下:Rar.exe a "D: est.rar" "D: est"

 1  static void Main(string[] args)
 2         {
 3             const string RARToolName = "Rar.exe";        //Rar命令行exe
 4             string compressionFileName = "D:\test.rar"; //压缩后的文件名
 5             string sourceFolderName = "D:\test";        //要压缩的文件夹
 6 
 7             Process p = new Process();
 8             ProcessStartInfo startInfo = new ProcessStartInfo();
 9             startInfo.FileName = RARToolName;
10             startInfo.CreateNoWindow = false;
11             startInfo.UseShellExecute = false;
12             startInfo.Arguments = string.Format("{0} {1} {2}","a",compressionFileName,sourceFolderName);
13             p.StartInfo = startInfo;
14             p.Start();
15         }

运行结果如下

打开D盘,会看到test.rar

解压Rar压缩文件

语法如下:Rar.exe x "D: est.rar" "D: est"

 1 const string RARToolName = "Rar.exe";        //Rar命令行exe
 2             string compressionFileName = "D:\test.rar"; //指定压缩文件名
 3             string sourceFolderName = "D:\test";   //要解压到的文件夹
 4 
 5             Process p = new Process();
 6             ProcessStartInfo startInfo = new ProcessStartInfo();
 7             startInfo.FileName = RARToolName;
 8             startInfo.CreateNoWindow = false;
 9             startInfo.UseShellExecute = false;
10             startInfo.Arguments = string.Format("{0} {1} {2}","x",compressionFileName,sourceFolderName);
11             p.StartInfo = startInfo;
12             p.Start();

这里还有一个操作,就是可以把图片和RAR压缩文件合并成一个文件

首先准备一个RAR文件,一个图片文件

 1   static void Main(string[] args)
 2         {
 3             string imageFilePath = "D:\2.jpg";            //图片文件路径
 4             string rarFilePath = "D:\test.rar";           //压缩文件路径
 5             string command = string.Format("copy /b {0} + {1} = {0}",imageFilePath,rarFilePath);  //命令
 6 
 7             Process p = new Process();
 8             ProcessStartInfo startInfo = new ProcessStartInfo();
 9             startInfo.FileName = "cmd.exe";
10             startInfo.UseShellExecute = false;    
11             startInfo.CreateNoWindow = false;
12             startInfo.RedirectStandardInput = true;
13             startInfo.RedirectStandardOutput = true;
14             p.StartInfo = startInfo;          
15             p.Start();
16             p.StandardInput.WriteLine(command + "&exit");
17             p.StandardInput.AutoFlush = true;      
18             p.WaitForExit();
19             p.Close();
20             Console.WriteLine("执行成功");
21 }

执行完成后,会发现图片文件变大了

此时我们只要将文件后缀修改为.rar,就可以以压缩文件的方式打开该文件。修改为.jpg,可以正常打开图片。

原文地址:https://www.cnblogs.com/zhaotianff/p/9408695.html