在richtextbox中加载密码word文档

本文关键字:word 文档 密码 加载 richtextbox | 更新日期: 2023-09-27 18:09:45

我使用

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

但是如何打开带密码的word文档呢?如何绕过密码到richtextbox ?

在richtextbox中加载密码word文档

您可以使用互操作打开密码保护的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");
}

你可以根据你的需求格式化和修改代码。