Hello,
I am using the document.Range.Replace method to replace Text in a word document. Normally i prefer working with streams, but in this case working with stream destroy the file after replacing text in it.
I made a sample method:
public override void ApplyTextTest()
{
// First I use a regular file
string fileName = "C:\Temp\Test";
Document doc = new Document(fileName + ".docx");
doc.Range.Replace("##Company.CompanyPart.CompanyDesc##", "replace it", new FindReplaceOptions());
doc.Range.Replace("##=US.TestFunct.CompanyCode##", "replace it too", new FindReplaceOptions());
doc.Range.Replace("##=US.TestFunct.Auchschon##", "replace it also", new FindReplaceOptions());
// i am saving the result into another file (could save it to the original file, which would also work)
doc.Save(fileName + "_replaced.docx");
// this works fine
// now i take the origin file and open it in a stream
FileStream stream = new FileStream(fileName + ".docx", FileMode.Open, FileAccess.ReadWrite);
try
{
doc = new Document(stream);
doc.Range.Replace("##Company.CompanyPart.CompanyDesc##", "replace it", new FindReplaceOptions());
doc.Range.Replace("##=US.TestFunct.CompanyCode##", "replace it too", new FindReplaceOptions());
doc.Range.Replace("##=US.TestFunct.Auchschon##", "replace it also", new FindReplaceOptions());
// i am saving the changes to the original stream
doc.Save(stream, SaveFormat.Docx);
}
finally
{
stream.Close();
stream.Dispose();
}
// now the file is rendered unusable…
}
Am I doing something wrong?
Thanks in advance
Stefan