Stack Overflow with Word Automation Replace - SOLVED
When performing Word automation, Word will sometimes throw a System.StackOverflowException, which you cannot catch, while performing a find/replace operation. It is usually the Find.Replacement.ClearFormatting(); call that leads to this exception.
The solution to this is simple, use late binding. In fact, it is recommended that you use late binding whenever performing office automation.
The resulting code would be something like
object Selection = oWord.Selection;
object myFind = oWord.Selection.Find;
object Optional = Type.Missing;
object wd = Word.WdReplace.wdReplaceAll;
object[] Parameters;
object findText = "Findtext";
object replaceText = "Replacetext";
Parameters = new object[15];
Parameters[0] = findText;
Parameters[1] = Optional;
Parameters[2] = Optional;
Parameters[3] = Optional;
Parameters[4] = Optional;
Parameters[5] = Optional;
Parameters[6] = Optional;
Parameters[7] = Optional;
Parameters[8] = Optional;
Parameters[9] = replaceText;
Parameters[10] = wd;
Parameters[11] = Optional;
Parameters[12] = Optional;
Parameters[13] = Optional;
Parameters[14] = Optional;
myFind.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, null, myFind, Parameters);
Don't forget to free the objects you have used
System.Runtime.InteropServices.Marshal.ReleaseComObject(oFind);
oFind = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSelection);
oSelection = null;
This succesfully resolved the problem for me.
Sources:
- http://www.digitalsupporttech.com/forum/user/viewthread?thread=326374
- http://www.digitalsupporttech.com/forum/user/viewthread?thread=326374
Labels: programming



0 Comments:
Post a Comment
<< Home