With VS2010 and .Net 4, working with the office interops has become a lot easier. This article gives a step by step view of how to open a word document without needing the tools of Visual Studio Tools for Office (VSTO). *

The following topics are demonstrated:

  1. Open and properly close a Word Document.
  2. Write to a Word document.
  3. Remove the Word document’s meta data.
  4. Properly close the Word Application and clean up resources opened by the underlying Office Interop calls.
  5. Properly cast method calls to specific interops to avoid “Ambiguity between method” issue CS0467 C# compiler warning.
  6. Why the developer no longer has to reference null when passing in optional parameters to COM objects thanks to .Net 4.

Steps

  1. In VS2010 create a Console Application.
  2. In the Solutions Explorer right click on the References folder and select Add Reference.  In the .Net tab search for
    Microsoft.Office.Interop.Word.
    Note you can use version 12 or version 14; but you might as well use the latest 14.  
  3. Insert the following usings:
    using Microsoft.Office.Interop.Word;
  4. Create an existing Word document. The example code below uses an existing document at C:\TestDoc.docx.
  5. Insert this code:
    Application ap = new Application();
    
    try
    {
    
        Document doc = ap.Documents.Open( @"C:\TestDoc.docx", ReadOnly: false, Visible: false );
        doc.Activate();
    
        Selection sel =  ap.Selection;
    
        if ( sel != null )
        {
            switch ( sel.Type )
            {
                case WdSelectionType.wdSelectionIP:
                    sel.TypeText( DateTime.Now.ToString() );
                    sel.TypeParagraph();
                    break;
    
                default:
                    Console.WriteLine( "Selection type not handled; no writing done" );
                    break;
    
            }
    
            // Remove all meta data.
            doc.RemoveDocumentInformation( WdRemoveDocInfoType.wdRDIAll );
    
            ap.Documents.Save( NoPrompt: true, OriginalFormat: true );
    
        }
        else
        {
            Console.WriteLine( "Unable to acquire Selection...no writing to document done.." );
        }
    
        ap.Documents.Close( SaveChanges: false, OriginalFormat: false, RouteDocument: false );
    
    }
    catch ( Exception ex )
    {
        Console.WriteLine( "Exception Caught: " + ex.Message ); // Could be that the document is already open (/) or Word is in Memory(?)
    }
    finally
    {
        // Ambiguity between method 'Microsoft.Office.Interop.Word._Application.Quit(ref object, ref object, ref object)' and non-method 'Microsoft.Office.Interop.Word.ApplicationEvents4_Event.Quit'. Using method group.
        // ap.Quit( SaveChanges: false, OriginalFormat: false, RouteDocument: false );
        ( (_Application)ap ).Quit( SaveChanges: false, OriginalFormat: false, RouteDocument: false );
    
        System.Runtime.InteropServices.Marshal.ReleaseComObject( ap );
    }

Explanation

  • Line 1: Open Word application object found in the Microsoft.Office.Interop.Word namespace.
  • Line 6: Open up the Word document we are interested in. This is first instance of using named parameters in calling the underlying COM functionality.
  • Line 7: Activate makes sure our document has focus in the event that Word is already open.
  • Line 9-17: This code is a template to working with a selection and its type. Word distinguishes areas of interest by selections. Our selection is at the beginning of the document. When we get the selection we write the current date and time (line 16).
  • Line 27: Remove all of the meta data of the document. This is not required for writing, just as an added bonus of how-to.
  • Line 29: Save what we have done.
  • Line 37: Close the document.
  • Line 48: In line 47 if we call without the cast we get the ambiguity warning message from the compiler. By casting to the Application interface we avoid that warning.
  • Line 50: Release any COM handles or resources we may have inadvertently gotten in this process.

 

* For the record VSTO is only needed when we are creating a smart document or an addin to one of the office applications. This is pure interop programming and not VSTO.

Share