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 是否包含当前目录
)
测试代码如下:
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#压缩和解压文件的更多相关文章
- 【转】Java压缩和解压文件工具类ZipUtil
特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...
- 压缩和解压文件:tar gzip bzip2 compress(转)
tar[必要参数][选择参数][文件] 压缩:tar -czvf filename.tar.gz targetfile解压:tar -zxvf filename.tar.gz参数说明: -c 建立新的 ...
- linux 压缩和解压文件
一.压缩:20120715文件下面所有的文件 如下: tar -zcvf 20120715.tar.gz 20120715* 二.解压20120715.tar.gz压缩包 如下: tar -xzvf ...
- 使用GZipStream压缩和解压文件
最近做了一个用.NET里的GZipStream压缩解压缩gzip文件的小程序. GZipStream在System.IO.Compression底下,使用起来也很简单.虽然GZipStream是Str ...
- C# 压缩和解压文件(SharpZipLib)
先从网上下载ICSharpCode.SharpZipLib.dll类库 将文件或文件夹压缩为zip,函数如下 /// <summary> /// 压缩文件 /// </summary ...
- c#调用WinRAR软件压缩和解压文件
using System; using System.Collections.Generic; using System.Web; using System.IO; using System.Linq ...
- linux压缩和解压文件命令
tar 解包:tar zxvf filename.tar 打包:tar czvf filename.tar dirnamegz命令 解压1:gunzip filename.gz 解压2:gzi ...
- Android_JarZip压缩和解压文件
本文资料来自<android开发权威指南> AndroidSDK中提供了java.util.jar和java.util.zip包中的若干类和接口来完成. 压缩文件基本步骤: 1.创 ...
- metro压缩和解压文件
在1.zip中增加一张新图片StorageFile jpg = await KnownFolders.PicturesLibrary.GetFileAsync("1.jpg"); ...
随机推荐
- Grafana 在添加邮件和钉钉报警之后不报警的原因是没有重启grafana 不生效重启。
即使在grafana页面上面添加也需要重启.配置邮件配置文件更需要重启. systemctl restart grafana-server.service
- nodejs设置淘宝镜像
nodeJS的资源仓库在国内使用过程中,偶尔会遇到各种资源问题,通常设置为淘宝的镜像,网上很多说法是安装淘宝镜像,即$ npm install -g cnpm --registry=https://r ...
- flutter 不规则底部工具栏实现
import 'package:flutter/material.dart'; import 'each_view.dart'; class BottomAppBarDemo extends Stat ...
- django 实战3 simpleui
pip3 install django-import-export pip3 install django-simpleui pip3 install mysqlclient python3 mana ...
- ES6深入浅出-7 新版的类(上集)-2.介绍JS中的类
声明对象原型,公有属性. obj对象,它用一个属性__proto__记录了自己的原型 改掉它的原型为公有属性.那么obj这个对象及有了hi的方法.因为obj自己没有hi.那么就去自己的原型上去找了. ...
- mybatis 级联
级联是一个数据库实体的概念.一对多的级联,一对多的级联,在MyBatis中还有一种被称为鉴别器的级联,它是一种可以选择具体实现类的级联. 级联不是必须的,级联的好处是获取关联数据十分便捷,但是级联过多 ...
- SharpGL学习笔记(一) 平台构建与Opengl的hello World (转)
(一)平台构建与Opengl的hello World OpenGL就是3d绘图的API,微软针和它竞争推出D3D,也就是玩游戏时最常见的DirectorX组件中的3d功能. 所以不要指望windows ...
- 【2B设计】途牛商旅全案设计
整体设计方案: 途牛商旅全案设计 https://www.uisdc.com/tuniu-business-travel
- 如何修改WAMPServer默认的网站路径地址
通常,我们安装WAMPServer集成的PHP开发环境之后,默认的网站路径地址是其安装目录下子文件夹:"wamp/www/".那么我们怎么修改网站地址到自己指定的路径呢?本篇经验将 ...
- adb中文乱码问题怎么解决?
1.chcp 65001 执行完命令后 2.在cmd命令弹出的终端页面,右键单击属性设置成字体Lucida Console ,设置完成就解决了 adb 中文乱码问题