XmlException while creating Document from password protected .odt file

I’m trying to determine whether the file is password protected or not:

try
{
    using (var ms = new MemoryStream(fileContents))
    {
        new Document(ms);
    }
}
catch (…)

where fileContents is byte array of contents of password protected .odt file.
I expect to catch IncorrectPasswordException, like in the case of .docx file, but instead i catch System.XmlException. When I’m trying to open the same exact file without password protection, everything goes fine.
Is this type of exception expected or will it be changed in the future, because it seems too general for this exact case?

Hi Nikita,

Thanks for your inquiry. Please use FileFormatInfo.IsEncrypted property to achieve your requirements. This property returns true if the document is encrypted and requires a password to open.

Please let us know if you have any more queries.

FileFormatInfo info = FileFormatUtil.DetectFileFormat(MyDir + "Document.doc");
Console.WriteLine("The document format is: " + FileFormatUtil.LoadFormatToExtension(info.LoadFormat));
Console.WriteLine("Document is encrypted: " + info.IsEncrypted);
Console.WriteLine("Document has a digital signature: " + info.HasDigitalSignature);

I need to pass byte[] to the function where the aforementioned code is run, while FileFormatInfo encapsulates the information about the file in the file system, which is not what I want in this case.

Hi Nikita,

Thanks for your inquiry. Please use FileFormatUtil.DetectFileFormat method (Stream) method. This method detects and returns the information about a format of a document stored in a stream.

Following code example shows how to use the FileFormatUtil methods to detect the format of a document without any extension and save it with the correct file extension.

Hope this helps you. Please let us know if you have any more queries.

FileStream fs = File.Open(MyDir + "document", FileMode.Open, FileAccess.Read);
byte[] fileBytes = new byte[fs.Length];
fs.Read(fileBytes, 0, (int)fs.Length);
fs.Close();
MemoryStream stream = new MemoryStream(fileBytes);
FileFormatInfo info = FileFormatUtil.DetectFileFormat(stream);
Console.WriteLine("The document format is: " + FileFormatUtil.LoadFormatToExtension(info.LoadFormat));

Thank you, that will solve my problem.

Hi Nikita,

Thanks for your feedback. Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.