Word Automation Within A Windows Service


Just because Microsoft says that you shouldn’t do something rarely stops developers from trying.

My task was to try to write a Windows Service replacement for a legacy application that saved a Word Document to text and then added headers for shipment to a client’s reporting system.  The legacy system was an old VB6 application that was brittle– not only was there the typical hard coding, but the system must be left in a logged in state because to take it out of that state would mean the system would shut down.

Service Debugger Helper

I knew that I wanted to write a Windows Service, because that would allow the service to run without a user logged in– definitely an improvement over the current system.  The trick is that it is very difficult to debug a Windows Service because you cannot stop it at run time–there’s no interface.

Enter the Service Debugger Helper.  With this slick little project in your solution, you can mimic the Service functions of Start, Pause, Continue and Stop and get all the power of the debugger to write your code.  Simply call your Service functions of the same name from this project.

Make Sure You Set the Permissions Correctly

The biggest headache I’ve had on the project has to do with permissions–what permissions the service has to have compared to a standard Windows Forms application.

At first, I gave the service the permissions that I had–assigning it the credentials for my user account figuring that this would allow the service to run Word as if it were my user.  That didn’t work.  Every time I would call Documents.Open, I would get null coming back.  My system would then create a new document, and have nothing to show for it after translation.

It wasn’t until I found a discussion about Documents.Open returning null that I found the source of the problem.  The Windows Component needed to have the interactive option set, instead of the launch one:

I can see under “Component Services->Computers->My Computer->DCOM Config->Microsoft Word Document”.  right click properties selection “Identity” tab…

Once I did this, the service works like a charm.

Of course I’m still waiting for our system to upgrade to Word 2007 so that I can use the XML parsing abilities of the format, but for now I have a system that seems to be performing well and meets the specifications.

Leave a Reply

Your email address will not be published. Required fields are marked *

CommentLuv badge