打开Word文档,除非它有C#的密码

时间:2012-11-16 12:17:12

标签: c# interop ms-word

我想要做的是运行word文档的文件夹,并使用tiff打印机将它们转换为.tif文件。问题是,如果我遇到一个带有密码的文档,它应该跳过文档而不提示要求输入密码,它应该全部保留在后台。

我可以看到Document类具有HasPassword属性,但在打开文档之前无法检查它。

word.Documents.OpenNoRepairDialog(@"c:\testfolder\testDocWithPw.docx", ReadOnly: true);

我还试图给密码一个emtpy参数,并尝试捕获错误代码。但我必须按取消提示要求密码才能到达那里。

Application word = new Application();
word.DisplayAlerts = WdAlertLevel.wdAlertsNone;
try
{
    word.Documents.OpenNoRepairDialog(@"c:\testfolder\Doc2.docx", ReadOnly: true, PasswordDocument: "");
    word.ActivePrinter = "TIFF Image Printer 10.0";
    Doc.PrintOut(); //printout untested for now
    Doc.Close(false);
}
catch (System.Runtime.InteropServices.COMException ex)
{
    if (ex.ErrorCode == 0x12345678)
    {
        //skip file and log file name and position for review
    }
}

提前谢谢

编辑:只是尝试用错误的密码提供密码,我可以使用错误代码部分,最好的部分是,当没有密码时,即使你给它一个密码也会打开文件。所以它基本上做我想要的。 在更糟糕的情况下,我猜我不应该打开的文件上有人密码,我可以检查hasPassword属性,如果我不能访问一个糟糕的密码文件。

2 个答案:

答案 0 :(得分:3)

我自己回答这个问题,所以我没有悬而未决的问题。 解决方法很简单,只需在打开密码时给出密码,如果你留下一个空字符串,它就像没有提出问题一样。然后可以捕获一个com异常并且可以处理它,但是我想要。

Application word = new Application();
word.DisplayAlerts = WdAlertLevel.wdAlertsNone;
try
{
    word.Documents.OpenNoRepairDialog(@"c:\testfolder\Doc2.docx", ReadOnly: true, PasswordDocument: "RandomButSurelyNotRightPassword");
    word.ActivePrinter = "TIFF Image Printer 10.0";
    Doc.PrintOut(); //printout untested for now
    Doc.Close(false);
}
catch (System.Runtime.InteropServices.COMException ex)
{
    if (ex.ErrorCode == 0x12345678)
    {
        //skip file and log file name and position for review
    }
}

答案 1 :(得分:0)

当我第一次尝试时

word.Documents.OpenNoRepairDialog(@"c:\testfolder\Doc2.docx", ReadOnly: true, PasswordDocument: "RandomButSurelyNotRightPassword");

当我打开没有密码的单词时,提示不成功。 然后我找到了

"RandomButSurelyNotRightPassword"

作为占位符密码太长了......