tags:

views:

127

answers:

3

I am using the MS Word COM API to print Word documents from C#. See below...

    internal void PrintWordFileUsingDefaultPrinter(System.IO.FileInfo file)
    {
        //Open the document.
        object fileName = file.FullName;
        Document doc = app.Documents.Open(
            ref fileName, 
            ref missing, 
            ref trueValue, 
            ref falseValue, 
            ref missing, 
            ref missing, 
            ref missing, 
            ref missing, 
            ref missing, 
            ref missing, 
            ref missing, 
            ref missing, 
            ref missing, 
            ref missing, 
            ref missing, 
            ref missing);

        //Send print job to the printer.
        doc.PrintOut(
            ref trueValue,
            ref falseValue,
            ref missing,
            ref missing,
            ref missing,
            ref missing,
            ref missing,
            ref missing,
            ref missing,
            ref missing,
            ref missing,
            ref missing,
            ref missing,
            ref missing,
            ref missing,
            ref missing,
            ref missing,
            ref missing);

        doc.Close(ref falseValue, ref missing, ref missing);

    }

You will see that I finish by calling doc.Close(). However even after calling this Word still locks my file and I am unable to process it further. Any idea how I can force word to release my file?

(Apart from closing the Word process itself? I don't want to do this as I need to print a HUGE number of documents and prefer not to re-open Word every time)

A: 

Can you try to set the object doc to null after you have finished processing it?

JonH
Surely that would just release the pointer, not do any closing? Either way, I tried but no luck :(
willem
A: 

You sure it's not background printing? If so, you could tell it to print syncronously. Does omitting the printing unlock the file on close?

Ruben Bartelink
Interesting idea. But no, I'm afraid commenting out the printOut command still has the same result.
willem
+1  A: 

You will have to call Marshal.ReleaseComObject for the instance of the document, to be able to release it.

e.g. Marshal.ReleaseComObject(doc);

You will also need to release the instance of Word.Application to free the word application instance from the memory.

shahkalpesh
Thanks. The problem was that I was not Releasing and Quitting Word application instances, so an OLD winword instance was actually locking my file. Thanks a mil!
willem