c# sharpcompress:如何检查进度

c# sharpcompress : How to check progress

IArchive rar = SharpCompress.Archive.Rar.RarArchive.Open(new FileInfo("ze.rar"), SharpCompress.Common.Options.None);
        rar.WriteToDirectory(Directory.GetCurrentDirectory() + "\DATA", SharpCompress.Common.ExtractOptions.Overwrite);

使用上面的代码我可以提取 rar 文件,但是我想通过控制台显示进度。如何查看进度?

这应该提供一个示例,说明如何计算提取操作的当前百分比。感谢@MathiasRJessen 指出 IArchive.WriteToDirectory 扩展的行为。

IArchive rar = SharpCompress.Archive.Rar.RarArchive.Open(new FileInfo("ze.rar"), SharpCompress.Common.Options.None);
string directory = Path.Combine(Directory.GetCurrentDirectory(), "DATA");

// Calculate the total extraction size.
double totalSize = rar.Entries.Where(e => !e.IsDirectory).Sum(e => e.Size);
long completed = 0;

// Use the same logic for extracting each file like IArchive.WriteToDirectory extension.
foreach (var entry in rar.Entries.Where(e => !e.IsDirectory))
{
    entry.WriteToDirectory(directory, ExtractOptions.Overwrite);

    // Track each individual extraction.
    completed += entry.Size;
    var percentage = completed / totalSize;
    // TODO do something with percentage.
}

实际上,我发现这段代码比答案更有效。

Well, this was not properly documented anywhere on the Internet. There were some possibilities, but they wouldn't calculate properly. This is a working Progress percentage calculation for decompressing archives in SharpCompress.

这是摘自我的解压Class,所以逻辑上有额外的信息。然而,重要的是将 'CompressedBytesRead' 转换为双倍,并将其划分为也应转换为双倍的存档的总大小。

`

public static double Percentage {get; set;}

public static long totalSize { get; set; }

public static void BeginDecompression(string fullFileName, string fileName)
{
    try
    {               

        var settings = new Configuration().GetSettings();

        CurrentExtractionName = (Path.GetFileNameWithoutExtension(fileName)); 


        StringHelpers.ItemInfo item = StringHelpers.GetItemInfo(fileName);

        string extractPath = settings.EmbyAutoOrganizeFolderPath + "\" +
                             (Path.GetFileNameWithoutExtension(fileName));
        Directory.CreateDirectory(extractPath);
        IArchive archive = ArchiveFactory.Open(fullFileName);

        // Calculate the total extraction size.
        totalSize = archive.TotalSize;

        Console.WriteLine(totalSize);

        foreach (IArchiveEntry entry in archive.Entries.Where(entry => !entry.IsDirectory))
        {
            archive.EntryExtractionEnd += FileMoveSuccess; 
            archive.CompressedBytesRead += Archive_CompressedBytesRead;
            entry.WriteToDirectory(extractPath, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);

        }

    }
    catch (Exception ex)
    {
        Console.WriteLine("Error: " + ex.Message);
    }
}

private static void Archive_CompressedBytesRead(object sender, CompressedBytesReadEventArgs e)
{            
    Percentage = ((double)e.CompressedBytesRead / (double)totalSize) * 100;

    Console.WriteLine(Percentage);
}

`

如果有人有更好的东西,我会洗耳恭听,但这将有助于实现进度条。