为了便于文件在网络中的传输和保存,通常将文件进行压缩操作,常用的压缩格式有rar、zip和7z,本文将介绍在C#中如何对这几种类型的文件进行压缩和解压,并提供一些在C#中解压缩文件的开源库。

在C#.NET中压缩解压rar文件

rar格式是一种具有专利文件的压缩格式,是一种商业压缩格式,不开源,对解码算法是公开的,但压缩算法是私有的,需要付费,如果需要在您的商业软件中使用rar格式进行解压缩,那么你需要为rar付费,rar在国内很流行是由于盗版的存在,正因为算法是不开源的,所以我们压缩rar并没有第三方的开源库可供选择,只能另寻出路。

针对rar的解压缩,我们通常使用winrar,几乎每台机器都安装了winrar,对于普通用户来说它提供基于用户界面的解压缩方式,另外,它也提供基于命令行的解压缩方式,这为我们在程序中解压缩rar格式提供了一个入口,我们可以在C#程序中调用rar的命令行程序实现解压缩,思路是这样的:

1、判断注册表确认用户机器是否安装winrar程序,如果安装取回winrar安装目录。

2、创建一个命令行执行进程。

3、通过winrar的命令行参数实现解压缩。

首先我们通过下面的代码判断用户计算机是否安装了winrar压缩工具:

如果已经安装winrar可通过如下代码返回winrar的安装位置,未安装则返回空字符串,最后并关闭注册表:

public static string ExistsWinRar()
{
string result = string.Empty; string key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe";
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(key);
if (registryKey != null)
{
result = registryKey.GetValue("").ToString();
}
registryKey.Close(); return result;
}
/// <summary>
/// 将格式为rar的压缩文件解压到指定的目录
/// </summary>
/// <param name="rarFileName">要解压rar文件的路径</param>
/// <param name="saveDir">解压后要保存到的目录</param>
public static void DeCompressRar(string rarFileName, string saveDir)
{
string regKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe";
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(regKey);
string winrarPath = registryKey.GetValue("").ToString();
registryKey.Close();
string winrarDir = System.IO.Path.GetDirectoryName(winrarPath);
String commandOptions = string.Format("x {0} {1} -y", rarFileName, saveDir); ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = System.IO.Path.Combine(winrarDir, "rar.exe");
processStartInfo.Arguments = commandOptions;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden; Process process = new Process();
process.StartInfo = processStartInfo;
process.Start();
process.WaitForExit();
process.Close();
}
/// <summary>
/// 将目录和文件压缩为rar格式并保存到指定的目录
/// </summary>
/// <param name="soruceDir">要压缩的文件夹目录</param>
/// <param name="rarFileName">压缩后的rar保存路径</param>
public static void CompressRar(string soruceDir, string rarFileName)
{
string regKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe";
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(regKey);
string winrarPath = registryKey.GetValue("").ToString();
registryKey.Close();
string winrarDir = System.IO.Path.GetDirectoryName(winrarPath);
String commandOptions = string.Format("a {0} {1} -r", rarFileName, soruceDir); ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = System.IO.Path.Combine(winrarDir, "rar.exe");
processStartInfo.Arguments = commandOptions;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process process = new Process();
process.StartInfo = processStartInfo;
process.Start();
process.WaitForExit();
process.Close();
}

在C#.NET中压缩解压zip文件

zip是一种免费开源的压缩格式,windows平台自带zip压缩和解压工具,由于算法是开源的,所以基于zip的解压缩开源库也很多,SharpZipLib是一个很不错的C#库,它能够解压缩zip、gzip和tar格式的文件,首先下载SharpZipLib解压后,在您的项目中引用ICSharpCode.SharpZLib.dll程序集即可,下面是一些关于SharpZipLib压缩和解压的示例。

ZipOutputStream zipOutStream = new ZipOutputStream(File.Create("my.zip"));
CreateFileZipEntry(zipOutStream, "file1.txt", "file1.txt");
CreateFileZipEntry(zipOutStream, @"folder1\folder2\folder3\file2.txt", "file2.txt");
zipOutStream.Close();
Directory.CreateDirectory("ZipOutPut");
ZipInputStream zipInputStream = new ZipInputStream(File.Open("my.zip", FileMode.Open));
ZipEntry zipEntryFromZippedFile = zipInputStream.GetNextEntry();
while (zipEntryFromZippedFile != null)
{
if (zipEntryFromZippedFile.IsFile)
{
FileInfo fInfo = new FileInfo(string.Format("ZipOutPut\\{0}", zipEntryFromZippedFile.Name));
if (!fInfo.Directory.Exists) fInfo.Directory.Create(); FileStream file = fInfo.Create();
byte[] bufferFromZip = new byte[zipInputStream.Length];
zipInputStream.Read(bufferFromZip, 0, bufferFromZip.Length);
file.Write(bufferFromZip, 0, bufferFromZip.Length);
file.Close();
}
zipEntryFromZippedFile = zipInputStream.GetNextEntry();
}
zipInputStream.Close();

使用.NET中自带的类解压缩zip文件

微软在System.IO.Compression命名空间有一些关于文件解压缩的类,如果只是希望压缩解压zip和gzip格式的文件,是个不错的选择,在NET Framework 4.5框架中,原生System.IO.Compression.FileSystem.dll程序集中新增了一个名为ZipFile的类,,让压缩和解压zip文件变得更简单,ZipFile的使用示例如下:

System.IO.Compression.ZipFile.CreateFromDirectory(@"e:\test", @"e:\test\test.zip"); //压缩
System.IO.Compression.ZipFile.ExtractToDirectory(@"e:\test\test.zip", @"e:\test"); //解压

支持格式最多的C#解压缩开源库

当您还苦苦在为上面的各种压缩格式发愁的时候,一个名为SharpCompress的C#框架被开源,您可以在搜索引擎中找到SharpCompress框架的开源代码,它支持:rar 7zip, zip, tar, tzip和bzip2格式的压缩和解压,下面的示例直接从rar格式文件读取并解压文件。

using (Stream stream = File.OpenRead(@"C:\Code\sharpcompress.rar"))
{
var reader = ReaderFactory.Open(stream);
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
Console.WriteLine(reader.Entry.FilePath);
reader.WriteEntryToDirectory(@"C:\temp");
}
}
}

零度最后的总结

关于rar和zip格式相比,rar的压缩率比zip要高,而且支持分卷压缩,但rar是商业软件,需要付费,zip压缩率不如rar那么高,但开源免费,7zip格式开源免费,压缩率较为满意,这些压缩格式各有优势,就微软平台和一些开源平台来说,一般采用的都是zip格式,因为它更容易通过编程的方式实现,比rar更加可靠,以上就是零度为您推荐的C#解压缩框架,感谢阅读,希望对您有所帮助。

http://www.tugberkugurlu.com/archive/net-4-5-to-support-zip-file-manipulation-out-of-the-box
https://github.com/adamhathcock/sharpcompress

使用C#压缩解压rar和zip格式文件的更多相关文章

  1. C#压缩或解压(rar和zip文件)

    /// <summary> /// 解压RAR和ZIP文件(需存在Winrar.exe(只要自己电脑上可以解压或压缩文件就存在Winrar.exe)) /// </summary&g ...

  2. 在Ubuntu系统中解压rar和zip文件的方法

    大家在以前的windows系统中会存有很多rar和zip格式的压缩文件,Ubuntu系统默认情况下对这些文件的支持不是很好,如果直接用"归档管理器"打开会提示错误,因此今天跟大家分 ...

  3. Linux解压rar、zip、war、tar文件

    在Linux上解压常见文件的命令: rar文件:rar e xxx.rar zip文件:unzip -xzvf xxx.zip war包:jar -xvf xxx.war tar包:tar -xzvf ...

  4. [Linux] 016 压缩解压命令

    1. 压缩解压命令:gzip 命令名称:gzip 命令所在路径:/bin/gzip 执行权限:所有用户 语法:gzip [文件] 功能描述:压缩文件 压缩后文件的格式:.gz 补充: 解压 .rar ...

  5. linux笔记:linux常用命令-压缩解压命令

    压缩解压命令:gzip(压缩文件,不保留原文件.这个命令不能压缩目录) 压缩解压命令:gunzip(解压.gz的压缩文件) 压缩解压命令:tar(打包压缩目录或者解压压缩文件.打包的意思是把目录打包成 ...

  6. linux命令:压缩解压命令

    压缩解压命令:gzip 命令名称:gzip 命令英文原意:GNU zip 命令所在路径:/bin/gzip 执行权限:所有用户 语法:gzip 选项  [文件] 功能描述:压缩文件 压缩后文件格式:g ...

  7. Linux常用命令6 压缩解压命令

    .zip是Linux和Windows共有的压缩格式 1.压缩解压命令:gzip 命令英文原意:GNU zip   命令所在路径:/bin/gzip 执行权限:所有用户 语法: gzip [文件]   ...

  8. 模块 shutil_zipfile_tarfile压缩解压

    shutil_zipfile_tarfile压缩解压 shutil 模块 高级的 文件.文件夹.压缩包 处理模块 shutil.copyfileobj(fsrc, fdst[, length]) #将 ...

  9. Linux下zip格式文件的解压缩和压缩

    Linux下zip格式文件的解压缩和压缩 Linux下的软件包很多都是压缩包,软件的安装就是解压缩对应的压缩包.所以,就需要熟练使用常用的压缩命令和解压缩命令.最常用的压缩格式有.tar.gz/tgz ...

随机推荐

  1. 让easyui的datagrid的field支持属性的子属性(field.childfield)

    如果不修改后台返回的数据格式,就只能修改easyui的源代码了. 首先在easyui的源代码中找到下面的部分,VS可以用 “var.*_.+=.*_.+\[.*_.+\];” 这个正则表达式来查找,会 ...

  2. JavaScript之正則表達式入门

    <html> <head><title>Js String 正則表達式</title><script>//边界符 js 中直接定义须要边界符 ...

  3. 显示vim当前颜色主题

    在vim内,查看colors_name :echo g:colors_name 如果值为空,那么默认为:default主题

  4. An example of using Pandas for regression

    An example of using Pandas for regression 这个例子来自这本书 - "Python for Data Analysis", 这本书的作者 W ...

  5. .NET url 的编码与解码

    举例: aaa.aspx?tag=.net%bc%bc%ca%f5 aaa.aspx?tag=.net%e6%8a%80%e6%9c%af看起来好像是不一样,其实他们都是对".net技术&q ...

  6. Oracle PLSQL Demo - 18.01管道function[查询零散的字段组成list管道返回]

    --PACKAGE CREATE OR REPLACE PACKAGE test_141213 is TYPE type_ref IS record( ENAME ), WORK_CITY ), SA ...

  7. LeetCode: Gray Code 解题报告

    Gray CodeThe gray code is a binary numeral system where two successive values differ in only one bit ...

  8. db2 查看进程 db2中的常用命令及使用方法

    一 高(重要度) 1 启动一个db 2实例使用: net start instanceName 2 停止一个db 2实例使用: net stop instanceName 3 启动配置助手: db2= ...

  9. 解决运行github项目build时间长问题

    运行github上的项目的时候,有时会build很长时间 可以打开项目所在目录修改这个文件:项目名XXX/gradle/wrapper/gradle-wrapper.properties 这个文件中的 ...

  10. (转) eclipse安装lombok

    lombok的官方网址:http://projectlombok.org/ 1. lombok的安装: 使用lombox是需要安装的,如果不安装,IDE则无法解析lombox注解,有两种方式可以安装l ...