在 richtextbox 中加载带密码的 word 文档
Load passworded word document in richtextbox
我使用
在 richtextbox 中打开 word 文档
richTextBoxEx1.LoadFile(@"c:.docx", RichTextBoxStreamType.PlainText);
但是如何打开带密码的word文档呢?
如何绕过 richtextbox 的密码?
您可以使用互操作打开受密码保护的 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");
}
您可以根据您的要求格式化和修改代码。
我使用
在 richtextbox 中打开 word 文档richTextBoxEx1.LoadFile(@"c:.docx", RichTextBoxStreamType.PlainText);
但是如何打开带密码的word文档呢? 如何绕过 richtextbox 的密码?
您可以使用互操作打开受密码保护的 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");
}
您可以根据您的要求格式化和修改代码。