Click here to Skip to main content
15,937,429 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my application, I am trying to access word document programmatically.
My C# code will write a paragraph text (its a marker/separator) into the active word document at particular time interval.

That part is working perfectly.
The problem is, the same document is being accessed by another Application at the same time which write some text into it.

But when i add the marker at a particular interval, it replaces the existing text added by the other application.
But it retains older markers, only the content written by other application is getting replaced.

My code is copied, please help to figure out.

using System;
using System.Reflection;
using log4net;
using log4net.Config;
using Word = Microsoft.Office.Interop.Word;

namespace WordOperation{

class Program {

 private static ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
 private static object _oMissing = System.Reflection.Missing.Value;
 private static object _oEndOfDoc = "\\endofdoc";
 private static object _oEoF = Word.WdUnits.wdStory;

 static void Main(string[] args)
   var wordApplication = new Word.ApplicationClass {Visible = true};
   Word.Document document = wordApplication.Documents.Add();
    while (true)
      object oRng = document.Bookmarks.get_Item(ref _oEndOfDoc).Range;
      Word.Paragraph markerParagraph = document.Content.Paragraphs.Add(ref oRng);
      markerParagraph.Range.Text = Common.MarkerTextContent;
      wordApplication.ActiveWindow.Selection.EndKey(ref _oEoF, ref _oMissing);
BillWoodruff 1-Jan-14 2:11am    
Isn't the real solution here locking the file while any one application is doing a write using log4net ?

Word, Excel documents and generally all file based programs are not databases and you should not expect to use them as such (multiple updates from different places).

You should rethink how you are doing things to avoid this.
Share this answer
Multiple updates and everything are working fine.
The problem was the latest text getting replaced.
I solved the issue by inserting just one line of code.. goto the end of the document.
wordApplication.ActiveWindow.Selection.EndKey(ref _oEoF, ref _oMissing);
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900