How to check whether a rar file is pwd protected?

Hi, Support:

How to know whether a Rar file is pwd protected.

Thanks for your help.

Hello, now the only way is trying to extract and catch an exception.

First case - file names are not encrypted.

using(var a = new RarArchive("data.rar"))
{
   try
   {
        using(var src = a.Entries[0].Open()) 
       //Open method raises ArgumentNullException of encrypted entry.
        {
             byte[] buffer = new byte[8192];
             int bytesRead;
             while ((bytesRead = src.Read(buffer, 0, buffer.Length)) > 0)
                   destination.Write(buffer, 0, bytesRead);                        
         }
      }
   catch (System.ArgumentNullException ex) {
        //ex.ParamName is "password"
        //ex.Message starts with "Password for decryption was not supplied."
   }
}

Alternatively, you can check if archive entry is RarArchiveEntryEncrypted.

using(var a = new RarArchive("data.rar"))
{
    if (a.Entries[0] is RarArchiveEntryEncrypted) {
        ...
    }
}

Second case - file names are encrypted.

try
{
    using(var a = new RarArchive("data.rar"))
    //Instantiation raises an InvalidOperationException
    {
       ...
    }
}
catch(System.InvalidOperationException ex)
{
    //ex.Message starts with "File names are encrypted"
}

Put it all together.

try
{
    using(var a = new RarArchive("data.rar"))
    {
       Stream src;
       if (a.Entries[0] is RarArchiveEntryEncrypted)
          src = a.Entries[0].Open("T0pSecret"));                 
       else src = a.Entries[0].Open());
              
       using(src)
       {
          ...
       }       
    }
}
catch(System.InvalidOperationException ex)
{
    //Check if file names are encrypted.
}

Thanks very much.

And as for zip/7z file, the same way to check password protected files? if not, what is the method?

You are correct. Encrypted 7z archive entry can be cast to SevenZipArchiveEntryEncrypted type. Encrypted zip entry can be cast to ArchiveEntryEncrypted type.