我在使用C#做word 功能开发时,遇到这个问题:使用 oDoc.Content.Find.Execute 方法替换指定内容。但是程序会抛出异常:
System.AccessViolationException”类型的未经处理的异常在 中发生
其他信息: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
word2007 sp3,没装过其他版本。
测试代码:以下代码放到button中就可用
代码:
private void testToolStripMenuItem_Click(object sender, EventArgs e)
{
string file = "d:/test.doc";
if (!File.Exists(file))
return;
object oMissing = System.Reflection.Missing.Value;
//打开文件
Word.Application oWord;
Word.Document oDoc;
oWord = new Word.Application();
oDoc = oWord.Documents.Open("d:/test.doc");
oDoc.Content.Find.Replacement.ClearFormatting();//此处必报错System.AccessViolationException
oDoc.Content.Find.ClearFormatting();
oDoc.Content.Find.Text = "${replace}";//需要被替换的文本
oDoc.Content.Find.Replacement.Text = "呵呵";//替换文本
//执行替换操作
oDoc.Content.Find.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, Word.WdReplace.wdReplaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
oDoc.SaveAs(file);
oDoc.Close();
oWord.Quit();
}
word中的内容:替换这个内容${replace},恩
尝试直接使用 oDoc.Content.Find.Execute方法,也不行,抛出异常的位置是oDoc.Content.Find。也就是只要是Find内容就会出错。
在网上查了很多,都没有找到解决办法。在线等。
------解决思路----------------------
oWord.Documents.Open("d:/test.doc");
试一下指定读写打开模式呢?
------解决思路----------------------
测试代码:以下代码放到button中就可用
没有道理啊