用SharpZipLib解压缩.tar.gz

本文关键字:gz tar 解压缩 SharpZipLib | 更新日期: 2023-09-27 17:53:16

我试图解压缩tar.gz在一个zip,但我不能

显示错误" cannot find central directory ",我不知道该怎么办。

首先,我在一个临时文件夹上解压缩zip,然后在该文件夹上搜索。tar.gz,并尝试解压缩,但由于该错误而崩溃,但我可以用winrar应用程序打开它,.tar.gz有一些文件夹和一些文件在里面。

这是我的代码:

var trash = Path.Combine(_temporalPath, "Trash");
        try
        {
            var zip = new FastZip();
            Directory.CreateDirectory(trash);
            zip.ExtractZip(_origin, trash, "");
            var gzip = Directory.GetFiles(trash, "*.tar.gz")[0];
            zip.ExtractZip(gzip, trash, FastZip.Overwrite.Always.ToString());
            File.Delete(gzip);
        }
        catch (Exception)
        {
            //IGNORE
        }

我搜索信息,但我只找到解压缩一个文件。输入图片描述

我需要的是打开tar.gz并从里面得到文件。

用SharpZipLib解压缩.tar.gz

使用SharpZipLib:

using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
public void ExtractTGZ(String gzArchiveName, String destFolder)
{
    Stream inStream = File.OpenRead(gzArchiveName);
    Stream gzipStream = new GZipInputStream(inStream);
    TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
    tarArchive.ExtractContents(destFolder);
    tarArchive.Close();
    gzipStream.Close();
    inStream.Close();
}

终于找到了。

var trash = Path.Combine(_temporalPath, "Trash");
        try
        {
            var zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
            Directory.CreateDirectory(trash);
            zip.ExtractZip(_origin, trash, null);
            var gzip = Directory.GetFiles(trash, "*.gz")[0];
            UnGzFile(gzip, Path.Combine(trash, Path.GetFileNameWithoutExtension(gzip)));
            File.Delete(gzip);
            var tar = Directory.GetFiles(trash, "*.tar")[0];
            var stream = File.OpenRead(tar);
            var tarArchive = ICSharpCode.SharpZipLib.Tar.TarArchive.CreateInputTarArchive(stream);
            tarArchive.ExtractContents(trash);
            tarArchive.Close();
            stream.Close();
            File.Delete(tar);
        }
        catch (Exception ex)
        {
            //IGNORE
        }

Sorry and Thanks

您可以简单地使用ZipFile class:

File.Move(source, Path.ChangeExtension(source, ".zip"));
ZipFile.ExtractToDirectory(Path.ChangeExtension(source, ".zip"), destination);

https://github.com/icsharpcode/SharpZipLib/wiki/FastZip

using System;
using ICSharpCode.SharpZipLib.Zip;
public void TestFastZipUnpack(string zipFileName, string targetDir) {
    FastZip fastZip = new FastZip();
    string fileFilter = null;
    // Will always overwrite if target filenames already exist
    fastZip.ExtractZip(zipFileName, targetDir, fileFilter);
}