Mahmoud Elgindy
Mahmoud Elgindy

Reputation: 114

Load passworded word document in richtextbox

I opened word document in richtextbox using

richTextBoxEx1.LoadFile(@"c:\3.docx", RichTextBoxStreamType.PlainText);

But how to open passworded word document ? How to bypass the password to richtextbox ?

Upvotes: 1

Views: 386

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

You can open a password protected word document using interop and then save it in rft format (that is not password protected) and can be shown flowless.

First add a reference to Microsoft.Office.Interop.Word

Then create a form with a RichTextBox on it and use these codes:

private delegate void OpenRtfDelegate();

private void Form1_Load(object sender, EventArgs e)
{
    try
    {
        //Create word application
        var word = new Microsoft.Office.Interop.Word.Application();

        //Attach an eventn handler to word_Quit to open rft file after word quit.
        //If you try to load rtf before word quit, you will receive an exception that says file is in use.
        ((Microsoft.Office.Interop.Word.ApplicationEvents4_Event)word).Quit += word_Quit; 

        //Open word document
        var document = word.Documents.Open(@"Path_To_Word_File.docx", PasswordDocument: "Password_Of_Word_File");

        //Save as rft
        document.SaveAs2(@"Path_To_RFT_File.rtf", FileFormat: Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatRTF);

        //Quit word
        ((Microsoft.Office.Interop.Word._Application)word).Quit(SaveChanges: Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private void word_Quit()
{
    //You should load rtf this way, because word_Quit is running in a differet thread
    this.richTextBox1.BeginInvoke(new OpenRtfDelegate(OpenRtf));
}

private void OpenRtf()
{
    this.richTextBox1.LoadFile(@"Path_To_RFT_File.rtf");
}

You can format and bend the code to your requirement.

Upvotes: 1

Related Questions