【问题标题】:Open Word document, unless it has password with C#打开 Word 文档,除非它有 C# 密码
【发布时间】:2012-11-16 12:17:11
【问题描述】:

我正在尝试做的是遍历 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 属性,如果我不应该访问密码错误的文档。

【问题讨论】:

  • 这篇文章会给idea
  • 这还取决于您使用的是较新的 .docx 文件格式还是较旧的 .doc 文件格式。
  • bonCodigo,这就是我尝试使用 try catch 方法 :),Lee Taylor 可以解释一下,doc 和 docx 在密码方面有什么区别。
  • @HenrikBøgelundLavstsen 查看此页面上的第一个答案social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/…
  • 真的,我仍然喜欢 ms 2003。永远不想使用 2007。但我不介意 2010。发现 this 猜测这是 Taylor 暗示的 :-)

标签: c# interop ms-word


【解决方案1】:

我自己回答这个问题,所以我没有悬而未决的问题。 解决方法很简单,打开的时候给个密码就行了,如果留一个空字符串,和不提问一样。然后可以捕获一个 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
    }
}

【讨论】:

    【解决方案2】:

    当我第一次尝试时

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

    当我打开一个没有密码的单词时,提示不成功。 然后我发现了

    "RandomButSurelyNotRightPassword"
    

    占位符密码太长...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多