在richtextbox中加载passworded word文档

时间:2015-08-24 13:28:46

标签: c# winforms richtextbox

我使用

在richtextbox中打开了word文档
richTextBoxEx1.LoadFile(@"c:\3.docx", RichTextBoxStreamType.PlainText);

但如何打开密码Word文档? 如何绕过密码到richtextbox?

1 个答案:

答案 0 :(得分:1)

您可以使用互操作打开受密码保护的Word文档,然后将其保存为rft格式(不受密码保护),并且可以显示为无流。

首先添加对Microsoft.Office.Interop.Word

的引用

然后创建一个包含RichTextBox的表单并使用以下代码:

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");
}

您可以根据需要格式化和弯曲代码。