本文主要是介绍(C#)使用sharpcompress压缩解压文件(.rar,.zip,tar.bz2,.7z,.tar.gz),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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);
}
这篇关于(C#)使用sharpcompress压缩解压文件(.rar,.zip,tar.bz2,.7z,.tar.gz)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!