Check excel file is protected (with and without password)

51 views Asked by At

I need to open an excel, and if it doesn't open, I need to determine if it's because of any of these cases: -- Excel is protected -- Excel is password protected -- Excel is corrupt.

I have to use a completely free library for commercial purposes. So after a lot of searching, I ended up choosing NPOI.

It's strange, but I originally tried to access the isprotected property of the excel to determinate which protection it has, but for that I need to open the excel first, which will fail if it really isprotected. I don't understand anything.

        using (var workbook = new XSSFWorkbook(stream))
        {
            return workbook.IsProtected;
        }

Now, I'm working with this idea. I try to open it, if everything goes well --> it's not protected with or without a password.

If I receive an exception, I try to open it with a random password, hoping that there will be some kind of exception that I can handle to determinate incorrect password and therefore it is using password or not password needed to determinate is protected without password...

But here I get blocked again. Can I use NPOI to open an excel with a password? Do you know of any other (commercially free) option that It can?

public static bool CanOpenExcel(IFormFile file)
{
    using (var stream = file.OpenReadStream())
    {
        try
        {
            using (var workbook = new XSSFWorkbook(stream))
            {
                return true;
            }
        }
        catch (InvalidFormatException ex)
        {
            return CanOpenProtectedExcel(stream);
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

private static bool CanOpenProtectedExcel(Stream stream)
{
    try
        {
//Cannot use the next line. It doesnt exist this constructor with 2 arguments
            using (var workbook = new XSSFWorkbook(stream, "dummyPassword"))
            {
                return false;
            }
        }
        catch (Exception ex)
        {
            return false;
        }
    }

It seemed like an easy thing to do at first, but, now, it's as complicated as it's getting me?

0

There are 0 answers