这里用两种方法实现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. 设定rsync开机自启动

    1.启用rsync服务systemctl enable rsync 2.打开rsync自己的开关,这个找了好多地方才找到的vi /etc/default/rsyncRSYNC_ENABLE=true

  2. imageButton和zoomButton

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...

  3. Python3基础 str : 字符串的逆序

             Python : 3.7.3          OS : Ubuntu 18.04.2 LTS         IDE : pycharm-community-2019.1.3    ...

  4. 算法习题---5.3字典(Uva10815)

    一:题目 给出一段英文,里面包含一些单词,空格和标点,单词不区分大小写,默认都为小写.按照字典序输出这些单词(这些单词不能有重复,字母全部变成小写) (一)样例输入 Adventures in Dis ...

  5. xml文档操作

    /** * */package com.gootrip.util; import java.io.ByteArrayOutputStream;import java.io.File;import ja ...

  6. websehll的使用和预防措施

    (1).webshell概念 webshell就是以asp.php.jsp或者cgi等网页文件形式存在的一种命令执行环境,也可以将其称做为一种网页后门.黑客在入侵了一个网站后,通常会将asp或php后 ...

  7. Unity 3D网络游戏实战 pdf

    Unity 3D网络游戏实战(全) 目录: 掌握Unity3D基本元素 1.1 简单的游戏 1.1.1在场景中创建一个立方体 1.1.2编写可以使立方体运动的程序 1.1.3测试游戏1.1.4总结1. ...

  8. FreeMarker的应用场景

      FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页.电子邮件.配置文件.源代码等)的通用工具. 它不是面向最终用户的,而是一个Java类库,是一 ...

  9. 【Leetcode_easy】949. Largest Time for Given Digits

    problem 949. Largest Time for Given Digits solution: class Solution { public: string largestTimeFrom ...

  10. react 生命周期图解

    参考地址:https://www.cnblogs.com/gdsblog/p/7348375.html