gpt4 book ai didi

c# - 用C#打开Word文档,除非它有密码

转载 作者:太空宇宙 更新时间:2023-11-03 21:53:25 34 4
gpt4 key购买 nike

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

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

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

我还尝试为密码提供一个空参数,并 try catch 错误代码。但我必须在提示输入密码时按取消才能到达那里。

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 属性,如果我不应该访问密码不正确的文档。

最佳答案

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

关于c# - 用C#打开Word文档,除非它有密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13416434/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com