sharpcompress安装方法
使用Nuget搜索sharpcompress,点击安装即可
1、.rar文件解压代码(不支持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.Key);
reader.WriteEntryToDirectory(@"C:\temp", new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
}
}
}
2、.zip文件压缩和解压代码
1).zip文件压缩代码
string filesPath = @"C:\Users\Administrator\source\repos\ConsoleApp1\ConsoleApp1";
using (var zip = File.OpenWrite("C:\\test.zip"))
using (var zipWriter = WriterFactory.Open(zip, ArchiveType.Zip, CompressionType.Deflate))
{
//foreach (var filePath in filesList)
//{
zipWriter.WriteAll(filesPath, "*", SearchOption.AllDirectories);
//}
}
2).zip文件解压代码
var archive = ArchiveFactory.Open(@"C:\\test.zip");
foreach (var entry in archive.Entries)
{
if (!entry.IsDirectory)
{
Console.WriteLine(entry.Key);
entry.WriteToDirectory(@"C:\temp", new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
}
}
3、.7z文件解压代码(不支持.7z压缩)
var archive = ArchiveFactory.Open(@"F:\Python35-32.7z");
foreach (var entry in archive.Entries)
{
if (!entry.IsDirectory)
{
Console.WriteLine(entry.Key);
entry.WriteToDirectory(@"C:\temp", new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
}
}
4、.tar.gz文件压缩代码
string filesPath = @"C:\Users\Administrator\source\repos\ConsoleApp1\ConsoleApp1";
using (var zip = File.OpenWrite("C:\\test.tar.gz"))
using (var zipWriter = WriterFactory.Open(zip, ArchiveType.Tar, CompressionType.GZip))
{
//foreach (var filePath in filesList)
//{
zipWriter.WriteAll(filesPath, "*", SearchOption.AllDirectories);
//}
}
5、.tar.bz2文件压缩代码
using (Stream stream = File.OpenWrite(tarbz2Path))
using (var writer = WriterFactory.Open(stream, ArchiveType.Tar, CompressionType.BZip2))
{
writer.WriteAll(filesPath, "*", SearchOption.AllDirectories);
}