.NET Core中使用SharpCompress库可以方便地进行多种格式的文件压缩和解压缩操作,支持的格式包括.rar, .zip, .tar.bz2, .7z, .tar.gz 等。SharpCompress是一个开源的.NET库,提供了对多种压缩格式的读写支持。本文主要介绍.NET Core(C#)使用sharpcompress压缩文件(.zip,.tar.bz2,.tar.gz)的代码以解压(.rar,.zip,.7z)的代码。

sharpcompress安装方法

使用Nuget搜索sharpcompress,点击 “安装” 即可。

相关文档VS(Visual Studio)中Nuget的使用

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);
}

推荐文档

相关文档

大家感兴趣的内容

随机列表