System.AccessViolationException:尝试读取或写入受保护的内存

时间:2010-04-30 12:01:08

标签: exception memory-management c#-3.0 ms-word office-interop

当我尝试在Windows Vista或Windows 7上运行的Word 2007中“查找并替换”时,出现以下异常。

  

System.AccessViolationException:   试图读或写受保护   记忆。这通常是一个迹象   其他内存已损坏。在   Microsoft.Office.Interop.Word.Find.Execute(对象&安培;   FindText,Object& MatchCase,Object&   MatchWholeWord,Object&   MatchWildcards,Object&   MatchSoundsLike,Object&   MatchAllWordForms,Object&向前,   对象和放大器;包裹,物体和格式,对象&   ReplaceWith,Object&替换,对象&   MatchKashida,Object& MatchDiacritics,   对象和放大器; MatchAlefHamza,Object&   MatchControl)

有没有解决方案?

我使用.NET3.5 C#。

********** CODE ****************

public static Application Open(string fileName)
{
    object fileNameAsObject = (object)fileName;
    Application wordApplication;            
    wordApplication = new Application();
    object readnly = false;
    object missing = System.Reflection.Missing.Value;
    wordApplication.Documents.Open(
        ref fileNameAsObject, ref missing, ref readnly, 
        ref missing,ref missing, ref missing, ref missing, 
        ref missing,ref missing, ref missing, ref missing, 
        ref missing,ref missing, ref missing, ref missing, 
        ref missing
    );

    return wordApplication;             
}

private static void ReplaceObject(
    ref Application wordApplication, 
    object ObjectTobeReplaced, object NewObject)
{
    // ++++++++Find Replace options Starts++++++

object findtext = ObjectTobeReplaced;
    object findreplacement = NewObject;
    object findforward = true;
    object findformat = false;
    object findwrap = WdFindWrap.wdFindContinue;
    object findmatchcase = false;
    object findmatchwholeword = false;
    object findmatchwildcards = false;
    object findmatchsoundslike = false;
    object findmatchallwordforms = false;
    object replace = 2; //find = 1; replace = 2
    object nevim = false;
    Range range = wordApplication.ActiveDocument.Content;
    range.Find.Execute(
        ref findtext, ref findmatchcase, ref findmatchwholeword, 
        ref findmatchwildcards,ref findmatchsoundslike, 
        ref findmatchallwordforms, ref findforward, ref findwrap,
        ref findformat, ref findreplacement, ref replace, 
        ref nevim, ref nevim, ref nevim, ref nevim
        );

2 个答案:

答案 0 :(得分:2)

重新安装Office后修复了问题:)...但仍然不知道导致问题的原因

答案 1 :(得分:1)

如果没有显示任何代码,这几乎无法回答。

一个(狂野的)猜测是,当你使用未初始化的Word进行交互时,你会提供一些类/结构,然后Word会尝试访问未初始化的内存。