Hi,
I have been trying to create a word document by copying the data from another pre-existing word document. There are certain fields in the newly created word document which needs to be replaced by some other texts. So i am trying to write a code which would search for the given word and replace it with the new one. The problem I am facing is whenever in the runtime the codes try to access the newly created word file and replace those texts it gives this particular error
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
Below is the snippet of code that i used to replace the texts
var newdcmnt = new Microsoft.Office.Interop.Word.Document();
var templatepath = Path.Combine(path, "OT_1stPage.doc"); ;
var wordapp = new Microsoft.Office.Interop.Word.Application();
var orgnldoc = wordapp.Documents.Open(templatepath);
orgnldoc.ActiveWindow.Selection.WholeStory();
orgnldoc.ActiveWindow.Selection.Copy();
float TopMargin = orgnldoc.PageSetup.TopMargin;
float BottomMargin = orgnldoc.PageSetup.BottomMargin;
float RightMargin = orgnldoc.PageSetup.RightMargin;
float LeftMargin = orgnldoc.PageSetup.LeftMargin;
newdcmnt.PageSetup.TopMargin = 25.0f;
newdcmnt.PageSetup.BottomMargin = 25.0f;
newdcmnt.PageSetup.RightMargin = 25.0f;
newdcmnt.PageSetup.LeftMargin = 25.0f;
orgnldoc.Close(SaveChanges: false, OriginalFormat: Type.Missing, RouteDocument: Type.Missing);
newdcmnt.ActiveWindow.Selection.PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdPasteDefault);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordapp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(orgnldoc);
GC.Collect();
object missingValue = Type.Missing;
foreach (Microsoft.Office.Interop.Word.Range tmpRange in newdcmnt.StoryRanges)
{
tmpRange.Find.Text = "xxTenderOpDtxx"//This Where I get the error
tmpRange.Find.Replacement.Text = "SomeText";
tmpRange.Find.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;
object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
tmpRange.Find.Execute(ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue, ref replaceAll,
ref missingValue, ref missingValue, ref missingValue, ref missingValue);
}
newdcmnt.SaveAs(pathString + "//" + GlobalVariable.xxTenderNoxx + ".doc");
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(newdcmnt);
Thank You
Regards
Bonny