Question

I would like to use SevenZipSharp in order to determine if a file is an archive. I know that it's possible because in explorer if I rename a .zip to .bmp, 7zip still recognises it as an archive.

--edit: In other words, I want 7zip to tell me if a file (no matter the extension) contains some kind of supported archive (zip, tar, rar, iso etc.)

Thanks, Fidel

Was it helpful?

Solution

static bool IsArchive(string filename)
{
    bool result = false;
    try
    {
        new ArchiveFile(File.OpenRead(filename));
        result = true;
    }
    catch
    {
        //log if you're going to do something about it
    }
    return result;
}

OTHER TIPS

The way you would determine if the file is an archive, is to actually try to feed it in to the SevenZipSharp library, and see if it succeeds or fails. However this is going to be a really slow process like your example you have a bunch of .zip files marked with the extension .bmp.

You don't need to use sevenzip to only know whether the file is an archive or not, It is suffice to check for the magic byte for various files.

For example:

Zip has initial 2 bytes 50 4B (PK)

RAR has initial 3 bytes 52 61 72 (Rar!)

SharpCompress does this easily as well.

bool x = SevenZipArchive.IsSevenZipFile(File.OpenRead(path));

I haven't used that library and the fact that there's no documentation doesn't help, but typically one tries to open the archive and if any error comes out, it might mean the file is not an archive (there's probably a specific error for that).

I'm not familiar with SevenZipSharp, but ZIP is a well documented file format, for example: ZIP File Format

Note the magic numbers at the start of the file and entries. You don't need any special API/library to detect a zip file, just read it as a normal file and check if it conforms to the format. If you don't feel like parsing the whole file, you could be lazy and just check the file signature is the one (or one of the ones) you're looking for: List of file signatures

7z.exe can be used to determine if a file is an archive:

static bool IsArchive(string filename)
{
    string _7z = @"C:\Program Files\7-Zip\7z.exe";

    bool result = false;
    using (Process p = new Process())
    {
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.FileName = _7z;
        p.StartInfo.Arguments = $"l \"{filename}\"";
        p.Start();
        string stdout = p.StandardOutput.ReadToEnd();
        string stderr = p.StandardError.ReadToEnd();

        if (stdout.Contains("Type = "))
        {
            result = true;
        }

        p.WaitForExit();
    }

    return result;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top