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:
- Open and properly close a Word Document.
- Write to a Word document.
- Remove the Word document’s meta data.
- Properly close the Word Application and clean up resources opened by the underlying Office Interop calls.
- Properly cast method calls to specific interops to avoid “Ambiguity between method” issue CS0467 C# compiler warning.
- Why the developer no longer has to reference null when passing in optional parameters to COM objects thanks to .Net 4.
Steps
- In VS2010 create a Console Application.
- 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. - Insert the following usings:
using Microsoft.Office.Interop.Word;
- Create an existing Word document. The example code below uses an existing document at C:\TestDoc.docx.
- 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.
Pingback: C# Open Word Documents using Visual Studio 2010 and .Net 4 at … | Source code bank
#1 by Emiliano Eloi Silva Barbosa on May 27, 2010 - 6:17 pm
Quote
I can not open a document in a web application.
#2 by OmegaMan on May 27, 2010 - 7:03 pm
Quote
You are running into permission issues. Sites are not allowed to access local items on a PC for virus reasons.
#3 by hermione7 on June 25, 2010 - 7:49 pm
Quote
hi,
I have Microsoft office 2010 (beta) and visual studio 2010 (ultimate). I did the steps that u put up, but I got an exception.
An unhandled exception of type ‘System.Runtime.InteropServices.COMException’ occurred in mscorlib.dll
Additional information: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0×80040154 (REGDB_E_CLASSNOTREG)).
Could you help me here?
I have been trying to simply open a word file(2010) from VS 2010 but I havent been successful as yet.
#4 by OmegaMan on June 26, 2010 - 8:28 am
Quote
Did you pull in Office v14 or v12?
#5 by hermione7 on June 26, 2010 - 4:39 pm
Quote
Thats the thing the COM tab has only v11 not 12 not 14
#6 by OmegaMan on June 26, 2010 - 5:33 pm
Quote
Hmmm, something is up with the beta. As mentioned in the software, this one is for v12 or v14. Try getting a non-beta copy. Sorry.
#7 by hermione7 on June 26, 2010 - 7:15 pm
Quote
I check in another laptop, the .Net tab has both Microsoft.Office.Interop.Word v12 and v14. I added v14 and tried again. But still I get the same error. Do u still think this is because of Word being beta? [This laptop also has VS2010 and Word 2010(beta)]
#8 by OmegaMan on June 26, 2010 - 8:02 pm
Quote
Hard to say…when I wrote the article both versions v14/12 where shown. It is possible that the interop work was not done for the beta you have(?). Firstly I recommend you get a current trial version or a licensed version. Otherwise try posting this question to TechnetInterop Development. GL HTH
#9 by Roschi on June 29, 2010 - 7:26 am
Quote
Hello
How can I open a wordfile and save it as PDF (ExportAsFixedFormat) from a Service?
#10 by OmegaMan on June 29, 2010 - 3:43 pm
Quote
This is out of the scope of this article. I recommend you post it to the Visual C# forum on MSDN GL
#11 by Mark on August 6, 2010 - 6:14 am
Quote
I like this article but would like to see more. How do write C# data to a new word document and format the data (bullets, fonts, etc.)
#12 by OmegaMan on August 8, 2010 - 9:04 pm
Quote
As I discuss here on my blog entitled, Tribal Knowledge: Working with Office Interops, one way to divine the inner workings of any office document and how to manage it via the interops is to record a macro of the process needed. Once done examine the vba code, it will show settings changes and other items of interest that can lead the way through the tribal knowledge of the interops. Most the object calls are the same under the covers…good luck
#13 by Manoj Pandey on August 28, 2010 - 1:04 am
Quote
I need code of console application in c# that read Word file
#14 by Tatiana on August 31, 2010 - 3:05 am
Quote
How can I subscribe to event of Word document starting?
In the Word 2003 I did it by assembly:System.ComponentModel.DescriptionAttribute(“OfficeStartupClass, Version=1.0, Class=ClassLibrary1.OfficeCodeBehind”)