这里用两种方法实现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 是否包含当前目录
)

测试代码如下:

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

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

运行

结果如下:

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

运行结果如下

解压zip压缩文件

使用 ZipFile类的ExtractToDirectory()方法

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

运行结果如下

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

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

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

运行结果如下

创建gz压缩文件

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

  static void Main(string[] args)
{
string filePath = "D:\\test"; //要添加到压缩文件的目录
string targetPath = "D:\\"; //压缩文件存放的目录 DirectoryInfo dirInfo = new DirectoryInfo(filePath); foreach (FileInfo fileInfo in dirInfo.GetFiles())
{
using (FileStream fsorg = fileInfo.OpenRead())
{
using (FileStream fs = File.Create(targetPath + fileInfo.Name + ".gz"))
{
using (GZipStream compressionStream = new GZipStream(fs,
CompressionMode.Compress))
{
fsorg.CopyTo(compressionStream);
}
}
}
}
}

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

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

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

解压gz压缩文件

   string compressFilePath = "D:\\4172212144245982608.jpg.gz";//压缩文件名

             FileInfo fileInfo = new FileInfo(compressFilePath);

             using (FileStream originalFileStream = fileInfo.OpenRead())
{
string currentFileName = fileInfo.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileInfo.Extension.Length); using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
}
}
}

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:\test.rar" "D:\test"

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

运行结果如下

打开D盘,会看到test.rar

解压Rar压缩文件

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

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

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

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

   static void Main(string[] args)
{
string imageFilePath = "D:\\2.jpg"; //图片文件路径
string rarFilePath = "D:\\test.rar"; //压缩文件路径
string command = string.Format("copy /b {0} + {1} = {0}",imageFilePath,rarFilePath); //命令 Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
p.StartInfo = startInfo;
p.Start();
p.StandardInput.WriteLine(command + "&exit");
p.StandardInput.AutoFlush = true;
p.WaitForExit();
p.Close();
Console.WriteLine("执行成功");
}

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

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

C#压缩和解压文件的更多相关文章

  1. 【转】Java压缩和解压文件工具类ZipUtil

    特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...

  2. 压缩和解压文件:tar gzip bzip2 compress(转)

    tar[必要参数][选择参数][文件] 压缩:tar -czvf filename.tar.gz targetfile解压:tar -zxvf filename.tar.gz参数说明: -c 建立新的 ...

  3. linux 压缩和解压文件

    一.压缩:20120715文件下面所有的文件 如下: tar -zcvf 20120715.tar.gz  20120715* 二.解压20120715.tar.gz压缩包 如下: tar -xzvf ...

  4. 使用GZipStream压缩和解压文件

    最近做了一个用.NET里的GZipStream压缩解压缩gzip文件的小程序. GZipStream在System.IO.Compression底下,使用起来也很简单.虽然GZipStream是Str ...

  5. C# 压缩和解压文件(SharpZipLib)

    先从网上下载ICSharpCode.SharpZipLib.dll类库 将文件或文件夹压缩为zip,函数如下 /// <summary> /// 压缩文件 /// </summary ...

  6. c#调用WinRAR软件压缩和解压文件

    using System; using System.Collections.Generic; using System.Web; using System.IO; using System.Linq ...

  7. linux压缩和解压文件命令

    tar  解包:tar zxvf filename.tar  打包:tar czvf filename.tar dirnamegz命令  解压1:gunzip filename.gz  解压2:gzi ...

  8. Android_JarZip压缩和解压文件

        本文资料来自<android开发权威指南> AndroidSDK中提供了java.util.jar和java.util.zip包中的若干类和接口来完成. 压缩文件基本步骤: 1.创 ...

  9. metro压缩和解压文件

    在1.zip中增加一张新图片StorageFile jpg = await KnownFolders.PicturesLibrary.GetFileAsync("1.jpg"); ...

随机推荐

  1. 廖雪峰Git教程1

    转自:https://www.liaoxuefeng.com/wiki/896043488029600 [安装Git] 最早Git是在Linux上开发的,很长一段时间内,Git也只能在Linux和Un ...

  2. ISO/IEC 9899:2011 条款6.2——概念

    6.2 概念 6.2.1 标识符的作用域 6.2.2 标识符的连接 6.2.3 标识符的名字空间 6.2.4 对象的存储持久性 6.2.5 类型 6.2.6 类型的表示 6.2.7 兼容类型与组合类型 ...

  3. Microsoft VBScript 运行时错误 错误 800a005e 无效使用 Null: Replace

    查看数据库   表的字段里面是否有空的字段. where 字段名 is null

  4. Spring中好玩的注解和接口

    测试中: 一.unit中集中基本注解,是必须掌握的. @BeforeClass – 表示在类中的任意public static void方法执行之前执行 @AfterClass – 表示在类中的任意p ...

  5. 算法习题---5.4反片语(Uva156)

    一:题目 输入一些单词,找出所有满足以下条件的单词:该单词不能通过字母重排得到输入文本中的另外一个单词.在判断是否满足条件时,字母不区分大小写,但在输出时应该保留输入中的大小写,按字典序进行排列 将输 ...

  6. 定时备份删除数据库sql

    1.备份数据库 mkdir -p /home/mysql/mysql_bak/ vi mysql_bak.sh #!/bin/bash #Shell Command For Backup MySQL ...

  7. js Date.parse()时区问题

    比较两个时间,parse() 方法可解析一个日期时间字符串,并返回 1970/1/1 午夜距离该日期时间的毫秒数.Date.parse时间多了8小时. 正确的方法: var nowDate = Dat ...

  8. NDK开发和NDK双进程守护

    https://www.jianshu.com/p/433b2c93c6a7 NDK进程守护 https://blog.csdn.net/k393393/article/details/7895435 ...

  9. CentOS7 配置sendmial + PHP mail函数发送邮件

    https://blog.csdn.net/jiabangok/article/details/51840556

  10. 【Leetcode_easy】1170. Compare Strings by Frequency of the Smallest Character

    problem 1170. Compare Strings by Frequency of the Smallest Character 参考 1. Leetcode_easy_1170. Compa ...