found several matches to my request, but not for word, so I open a new thread. I got a word document. After a specified text, I want to insert some lines.
My code looks like that:
public static class Program
{
static void Main(string[] args)
{
string Filename = @"D:\...\MasterDoc.docx";
string SearchFor = "Search this text and insert after it";
string DocText = string.Empty;
int InsertIndex = 0;
//Run or attach MS Word
Microsoft.Office.Interop.Word.Application wrdApp = RunOrAttachWordApplication();
//Open masterfile
Microsoft.Office.Interop.Word.Document doc = wrdApp.Documents.Open(Filename);
//Get complete range
Microsoft.Office.Interop.Word.Range rng = doc.Range();
//Get document text
DocText = rng.Text;
//Search indes to insert text
InsertIndex = DocText.IndexOf(SearchFor) + SearchFor.Length;
//Define range at location for text pasting
rng = doc.Range(InsertIndex, InsertIndex + 1);
//Write 'Test...' on specified location
rng.InsertAfter("Test...");
//Close document
doc.Close(); /*Right here I got a breakpoint and watch the result, so I do not need to save the document here*/
//Close application
wrdApp.Application.Quit();
wrdApp.Quit();
wrdApp = null;
System.GC.Collect();
System.Console.WriteLine("Ende...");
System.Console.ReadKey();
}
public static Microsoft.Office.Interop.Word.Application RunOrAttachWordApplication()
{
if(System.Diagnostics.Process.GetProcessesByName("Word").Length > 0)
{
return System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application") as Microsoft.Office.Interop.Word.Application;
}
else
{
return new Microsoft.Office.Interop.Word.Application();
}
}
}
Well, it works - but not correctly. The text is inserted about 50 digits before the location, I want.
Does anybody know, how to fix that or I could imagine, that there is a much better methode to do that. I cannot modify the Masterdocument as it is recreated everytime by another, external program.
Thank you very much and regards, Jan