这里用两种方法实现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. Xamarin图表开发基础教程(1)

    Xamarin图表开发基础教程(1) 在Xamarin图表开发中,最常用的框架是OxyPlot和Microcharts.其中,OxyOPlot提供多种多样的图表类型和丰富的图表功能,可以实现各种复杂的 ...

  2. npm WARN deprecated fsevents windows

    更新下 使用yarn貌似会帮助跳过这个问题: info fsevents@2.1.2: The platform "win32" is incompatible with this ...

  3. AS的常见问题

    版本问题 a.Gradle的版本 用于将代码和资源打包生成apk的编译脚本.此版本号究竟是啥得去studio的安装目录下查看b.Gradle插件的版本 com.android.tools.build: ...

  4. openresty开发系列30--openresty中使用http模块

    OpenResty默认没有提供Http客户端,需要使用第三方提供的插件 我们可以从github上搜索相应的客户端,比如https://github.com/pintsized/lua-resty-ht ...

  5. Jmeter之__CSVRead随机读取变量

    背景:当你需要从一些数据中随机的取值用的话可以用这个函数来实现__CSVRead __CSVRead函数用于对脚本进行参数化,当脚本中不同变量需要不同参数值时,可以考虑__CSVRead函数. _CS ...

  6. 查看Oracle中是否有锁表

    转: 查看Oracle中是否有锁表 2018-04-23 17:59 alapha 阅读(19450) 评论(0) 编辑 收藏 一.用dba用户登录,或者将用户赋权为DBA用户 命令: su - or ...

  7. window.location.href重定向失败的问题

    如题,在js中通过window.location.href=URL来跳转到另一个页面(也可以是另一个项目的另一个页面). 打开的页面地址是:www.a.com/project1/index 要跳转的页 ...

  8. libfacedetection

    libfacedetection测试 #include <stdio.h> #include <opencv2/opencv.hpp> #include <facedet ...

  9. Python高级笔记(七)魔法属性

    1. 私有属性 名字重整 print(Test.__dict__) {'__weakref__': <attribute '__weakref__' of 'Test' objects>, ...

  10. time zone list

    GMT UTC WET WET CET CET MET CET ECT CET EET EET MIT Pacific/Apia HST Pacific/Honolulu AST America/An ...