【问题标题】:Detect password protected word file检测密码保护的word文件
【发布时间】:2014-10-07 23:58:22
【问题描述】:

我正在使用“netoffice”库从 word 文件中提取文本。这应该是自动化的过程。

但是,当 word 文件受密码保护时,会显示警报窗口,因此用户需要输入密码。因为这是自动化的过程,用户不用输入密码,程序就停在这里。

如何检测 word 文件是否使用“netoffice”进行密码保护,如果不能,如何禁用警报窗口显示?

我尝试将 DisplayAlerts 设置为 WdAlertLevel.wdAlertsNone,但它不起作用。

【问题讨论】:

    标签: c# parsing ms-word netoffice


    【解决方案1】:

    以下代码将帮助您跳过受密码保护的文件:

            int iFilesWithPassword = 0;
            Factory.Initialize();
            Application wordApplication = new NetOffice.WordApi.Application();
    
            try
            {
                // Attempt to open existing document. If document is not password protected then 
                // passwordDocument parameter is simply ignored. If document is password protected
                // then an error is thrown and caught by the catch clause the follows, unless 
                // password is equal to "#$nonsense@!"!                              
                Document newDocument = wordApplication.Documents.Open(@"C:\Users\Giorgos\Desktop\myNextFile.doc",
                                                                      confirmConversions: false,
                                                                      addToRecentFiles: false,
                                                                      readOnly: false,
                                                                      passwordDocument: "#$nonsense@!");
    
    
    
                // read text of document
                string text = newDocument.Content.Text;
            }
            catch(Exception e)
            {
                Exception inner = e.InnerException;
    
                if (inner != null && inner.InnerException != null)
                {
                    inner = inner.InnerException;
                    string sErrorMessage = inner.Message;
    
                    if (sErrorMessage.Contains("The password is incorrect."))
                    {
                        iFilesWithPassword++;
                    }
                }
    
            }
            finally
            {
                // close word and dispose reference 
                wordApplication.Quit();
                wordApplication.Dispose();
            }
    

    【讨论】:

    • 我在 VS2012 中制作了一个控制台应用程序,使用 .NET Framework 4.0 和 NetOffice.dll v1.6。如果我省略了 passwordDocument 参数,我也会得到密码提示对话框。如果我添加 passwordDocument 参数,则不会显示任何对话框并引发异常。
    • 不确定programmer 的评论是否需要删除,因为此答案的已接受答案状态,但我可以确认此脚本的 VBS 版本确实按照giorgos-betsos 的建议工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 2018-05-15
    • 2011-01-09
    • 2012-09-05
    • 1970-01-01
    相关资源
    最近更新 更多