一.下载SharpCompress库
二.解压缩
(1)不带密码
/// <summary>
/// 解压缩(支持rar,zip)
/// </summary>
/// <param name="fromFilePath">待解压文件全路径</param>
/// <param name="outFileDirectory">解压文件后目录</param>
public static void Decompress(string fromFilePath, string outFileDirectory)
{
var archive = ArchiveFactory.Open(fromFilePath);
foreach (var entry in archive.Entries)
{
if (!entry.IsDirectory)
{
//Debug.WriteLine(entry.Key);
entry.WriteToDirectory(outFileDirectory, new ExtractionOptions { ExtractFullPath = true, Overwrite = true });
}
}
}
(2)带密码
/// <summary>
/// 解压缩加密的包(支持rar,zip)
/// </summary>
/// <param name="fromFilePath">待解压文件全路径</param>
/// <param name="outFileDirectory">解压文件后目录</param>
/// <param name="password">密码</param>
public static void DecompressWithPwd(string fromFilePath, string outFileDirectory, string password)
{
using (var archive = ArchiveFactory.Open(fromFilePath, new ReaderOptions { Password = password }))
{
foreach (var entry in archive.Entries)
{
if (!entry.IsDirectory)
{
//Debug.WriteLine(entry.Key);
entry.WriteToDirectory(outFileDirectory, new ExtractionOptions { ExtractFullPath = true, Overwrite = true });
}
}
}
}
三.压缩
/// <summary>
/// 压缩(zip格式)
/// </summary>
/// <param name="fromFileDirectory">待压缩目录</param>
/// <param name="outFilePath">压缩后文全件路径</param>
public static void ZipCompress(string fromFileDirectory, string outFilePath)
{
//解决中文乱码问题
SharpCompress.Common.ArchiveEncoding ArchiveEncoding = new SharpCompress.Common.ArchiveEncoding();
ArchiveEncoding.Default = Encoding.GetEncoding("utf-8");
SharpCompress.Writers.WriterOptions options = new SharpCompress.Writers.WriterOptions(CompressionType.Deflate);
options.ArchiveEncoding = ArchiveEncoding;
using (var archive = ZipArchive.Create())
{
archive.AddAllFromDirectory(fromFileDirectory);
using (var zip = File.OpenWrite(outFilePath))
archive.SaveTo(zip, options);
}
}
四.调用
//压缩
string fromFileDirectory = @"C:\test\我是目录";
string outFilePath = @"C:\压缩包1.zip";
CompressHelper.ZipCompress(fromFileDirectory, outFilePath);
//解压缩
string fromFilePath = @"C:\压缩包1.zip";
string outFileDirectory = @"C:\解压目录\压缩包1";
CompressHelper.Decompress(fromFilePath, outFileDirectory);
五.中文乱码问题
老版本直接加入下面一行代码就可以了
SharpCompress.Common.ArchiveEncoding.Default = Encoding.GetEncoding ("utf-8");
但是我使用的是0.23.0版本,.ArchiveEncoding已经从静态类改为普通类了,无法这样调用
参考:https://github.com/adamhathcock/sharpcompress/issues/268
最后发现:ArchiveEncoding类是OptionsBase的属性,而OptionsBase是WriterOptions的基类,ZipArchive的SaveTo方法带WriterOptions参数,那就ok了
参考:
wiki:https://github.com/adamhathcock/sharpcompress/wiki/API-Examples
支持类型:https://github.com/adamhathcock/sharpcompress/wiki/Supported-Formats
来源:oschina
链接:https://my.oschina.net/u/4381494/blog/3603309