这里用两种方法实现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. springIoC注解

    一.通过注解注入Bean @Component:组件(spring扫描包下有该注解的类) @ComponentScan(包名):组件扫描(spring扫描该包名下的类) @Configuration: ...

  2. 001 centos7中的安装

    以前学习过centos6.4的安装使用,然后新使用centos7,发现有些修改配置变化了,记录一下. 1.修改主机名 查看主机名: 修改: 二:ip的固定 1.参考文章 https://www.jia ...

  3. 使用AWS Lambda,API Gateway和S3 Storage快速调整图片大小

    https://www.obytes.com/blog/2019/image-resizing-on-the-fly-with-aws-lambda,-api-gateway,-and-s3-stor ...

  4. 从0开始学爬虫10之urllib和requests库与github/api的交互

    urllib库的使用 # coding=utf-8 import urllib2 import urllib # htpbin模拟的环境 URL_IP="http://10.11.0.215 ...

  5. JSOUP 爬虫

    作者QQ:1095737364    QQ群:123300273     欢迎加入! 1.mavne 依赖: <!--html 解析 : jsoup HTML parser library @ ...

  6. 0.9.0.RELEASE版本的spring cloud alibaba sentinel+feign降级处理实例

    既然用到了feign,那么主要是针对服务消费方的降级处理.我们基于0.9.0.RELEASE版本的spring cloud alibaba nacos+feign实例添油加醋,把sentinel功能加 ...

  7. 软件定义网络基础---SDN的产生

  8. Glide升级到4.x版本遇到的问题

    Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency ...

  9. Python初级 3 基本数学运算

    一. 四大基本运算操作符 1 加+ print(3 + 2) 2 减- print(3 - 2) 3 乘:* print(3 * 2) 4 除/, // print(3 / 2) print(3 // ...

  10. app--Android 稳定性测试方案

    标准的崩溃日志:Android 应用一般使用 Java 语言开发,在不作特殊处理的情况下,遇到未处理的异常时,会弹框提示“程序遇到异常,即将退出”(有些手机框中提示语不同, 或不弹框).同时会将异常的 ...