Aspose.Words for password protected documents

Hi,
I am using Aspose.Words to read contents from word documents. I am using
below code to open the password protected documents using Aspose.words.

try
{
    Document mainDoc = new Document(m_documentFile);
}
catch (Aspose.Words.IncorrectPasswordException)
{
    LoadOptions loadOps = new LoadOptions();
    loadOps.Password = "Test";
    mainDoc = new Document(m_documentFile, loadOps);
}

But my current requirement is to loop the list of passwords provided by the user and try to open the document utile the document opens successfully.
Please provide the sample code for this as soon as possible.
Thanks,
Dhivya

Hi Dhivya,
You can use the following code for this purpose.
string

m_documentFile = "PasswordProtected.docx";
Document mainDoc = null;
try
{
    mainDoc = new Document(m_documentFile);
}

catch (Aspose.Words.IncorrectPasswordException)
{
    string[] passwordsToTry = new string[]
    {
        "Pass1",
        "Pass2",
        "testpass",
        "Pass3"
    };

LoadOptions loadOps = new LoadOptions();

for (int i = 0; i <passwordsToTry.Length; i++)
{
    try
    {
        loadOps.Password = passwordsToTry[i];
        mainDoc = new Document(m_documentFile, loadOps);
        break;
    }

    catch (Aspose.Words.IncorrectPasswordException)
    {}
}

}
// Continue your operations
DocumentBuilder builder = new DocumentBuilder(mainDoc);

Best Regards,

1 Like

Hi,
Is there a way to open password protected document from a stream using Aspose.Words. I am getting “Unsupported file format” exception.

Stream stream = File.OpenRead(MyDir + "PasswordProtected.docx");
Document mainDoc = null;
try
{
    mainDoc = newDocument(stream);
}
catch (Aspose.Words.IncorrectPasswordException)
{
    string[] passwordsToTry = new string[]
    {
        "Pass1",
        "Pass2",
        "testpass",
        "Pass3"
    };
    LoadOptionsloadOps = new LoadOptions();
    for (int i = 0; i <passwordsToTry.Length; i++)
    {
        try
        {
            loadOps.Password = passwordsToTry[i];
            mainDoc = newDocument(stream, loadOps);
            break;
        }
        catch (Aspose.Words.IncorrectPasswordException)
        {}
    }
}

Thanks,
Dhivya

Hi Dhivya,
You can use the following code to read from stream.

string m_documentFile = "PasswordProtected.docx";
MemoryStream ms = new MemoryStream(File.ReadAllBytes(m_documentFile));

Document mainDoc = null;
try
{
    mainDoc = new Document(ms);
}

Best Regards,