代码之家  ›  专栏  ›  技术社区  ›  robob

Word2007:执行Selection.Find.execute时未处理访问冲突异常

  •  0
  • robob  · 技术社区  · 16 年前

    我试图解释我的环境。

    我有一个用C#编写的小应用程序,使用WinForms并通过InteropServices(Word.dll)调用Word,在Word中创建新文档(引发Word2007实例)。所有代码都在.NETFramework 3.5上运行。在C#代码中,我创建文档,然后在其中搜索要替换的内容。

    该程序仅在某些机器上产生引用的错误,而在其他机器上正确运行。

    以下是代码片段:

    WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    WordApp.Visible = false;
    ...
    this.copDoc = WordApp.Documents.Add(ref template,
                                                ref missing,
                                                ref missing,
                                                ref isVisible);
    
                    this.copDoc.Activate();
    ...
    WordApp.Selection.Find.Execute(ref textData, ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
    
    if (WordApp.Selection.Find.Found)
    {
        Range r = WordApp.Selection.Range;
        r.Text = DateTime.Today.ToLongDateString();
    }
    ...
    

    当代码以粗体执行第行时,将引发“访问冲突”异常,并显示消息“试图读取或写入受保护内存”。这通常表示其他内存已损坏。“。如果我对这段代码进行注释,那么文档就是创建的,这可能意味着异常与整个单词无关,而只与其中某些特定的配置有关。

    例外情况如下:

    'EdAg.exe': Loaded 'C:\Windows\assembly\GAC\Microsoft.Office.Interop.Word\12.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Word.dll', Binary was not built with debug information.
    'EdAg.exe' (Managed): Loaded 'C:\Windows\assembly\GAC\Microsoft.Office.Interop.Word\12.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Word.dll'
    First-chance exception at 0x45c7a6f3 in EdAg.exe: 0xC0000005: Access violation.
    First-chance exception at 0x6b815095 in EdAg.exe: 0xC0000005: Access violation reading location 0x45c7a6f3.
    First-chance exception at 0x6b815095 in EdAg.exe: 0xC0000005: Access violation reading location 0x45c7a6f3.
    

    有人能给我建议一种更合理的方法,而不是重新安装Word 2007吗?

    1 回复  |  直到 13 年前
        1
  •  0
  •   Andy Jacobs    16 年前

    机器上的问题是否与异常一致,还是间歇性的?

    如果一致,我不知道解决方案,但首先检查这些机器是否关闭了UAC(即,添加到Vista中的东西,当它认为有东西试图改变你的电脑时会提示你)(或与工作机器相反)。

    与此相关的是,当您使用COM时,当您试图从未受驱动的应用程序到受特权的应用程序(例如,以管理员身份启动)进行对话时,您可能会遇到这样的安全访问冲突。例如,如果有人以管理员身份启动您的应用程序(甚至可能是从以管理员身份运行的VS启动),而Word已经不是以管理员身份运行,则Windows将无法启动Word的另一个实例,并且不会让这两个实例对话,因此COM将失败。