Word Automation from C# vs. VB.NET

I recently received a question about doing some Word automation using .NET, and I saw an interesting little difference between the C# and VB.NET calling into the Interop Assembly for certain properties/methods…

If I take VBA or VB6 code that works, and convert it to the almost identical VB.NET code … (after adding a reference to Word in my VB.NET project);

Dim wordApp As New Word.Application()
Dim newDoc As
Word.Document = wordApp.Documents.Add
newDoc.Range.Text = “Test”
newDoc.AttachedTemplate = “C:\….\Macmillan.dot”
wordApp.Visible =
True


It works fine, but in C# I get an error setting the AttachedTemplate property;

error CS1545: Property, indexer, or event ‘AttachedTemplate’ is not supported by the language; try directly calling accessor methods ‘Word._Document.get_AttachedTemplate()’ or ‘Word._Document.set_AttachedTemplate(ref object)’

object missing = System.Reflection.Missing.Value;
Word.ApplicationClass wordApp =
new
Word.ApplicationClass();
Word.Document newDoc = wordApp.Documents.Add(
ref missing, ref missing, ref missing, ref
missing);
newDoc.Range(
ref missing,ref
missing).Text = “Test”;
newDoc.AttachedTemplate =  @”C:\….\Macmillan.dot”;
wordApp.Visible =
true;

I was able to make it work by writing the code like this;

object missing = System.Reflection.Missing.Value;
Word.ApplicationClass wordApp =
new
Word.ApplicationClass();
Word.Document newDoc = wordApp.Documents.Add(
ref missing, ref missing, ref missing, ref missing); newDoc.Range(ref missing,ref missing).Text = “Test”;
object templateName = (object
)@”C:\….\Macmillan.dot”;
newDoc.set_AttachedTemplate(
ref
templateName);
wordApp.Visible =
true;

I was interested in finding out more about this error so I asked around internally and had it explained to me quite quickly. Looking into the type-library for Word and then the IL of the Interop Assembly would have likely provided the answer as well, but I’m glad I didn’t have to get into that. I’ll try to pass the explanation along without mangling it too much in the translation (feel free to correct me if you can, or add additional details). Some properties of COM libraries are actually methods that support one or parameters, which is cool with VBA/VB6 as they supported this type of property as well, but they are translated (correctly it seems) by TlbImp.exe as methods (set_AttachedTemplate, get_AttachedTemplate)… VB.NET does some additional work for you so that you can still code against these property/methods as properties, but in C# you have to use them as methods. Interesting stuff, and likely a bit of a gotcha for people trying to move VBA code into .NET.

[Listening to: In the Air Tonight – Phil Collins – Miami Vice (05:29)]
Word Automation from C# vs. VB.NET

29 Responses

  1. I played with Word 11.0 COM on VB.Net platform. The word automation seems like providing writing to word document and changing the content, layout etc. Is there any way to read from the Word Document Preserving Style? Say suppose you are reading first line of Document having Font Size = 18 and Font color = Blue, What properties do I need to retrieve through VB.Net or VC#.net coding?

    Thanks.

    Mansi February 5, 2005 at 3:03 am #
  2. Thanks for your blog – having precisely the same issues myself today.

    Actually, perhaps a bit worse. Im using setter properties, and for some reason when converted to C# they require 2 parameters – the original set value, and something else (type object)…I have no idea what?

    Ben May 19, 2005 at 1:19 am #
  3. Hey, i got a problem, when I try to open the document I noticed that the winword process is fired but I can’t see the word document opened. My code is exactly the same as the one above. any Idea?

    Armando May 24, 2005 at 5:21 pm #
  4. Hi,
    What’s the best way from C# perspective to open a word document in both conditions, one in which user has already opened a Word app and another when no word app was running?

    Looks like there is no best way to do this. We are currently using the following code.

    <code>
    Type typWordApp = typeof(Word.Application);
    if (typWordApp!=null)
    {
    try
    {
    WordApplication=(Word.ApplicationClass)System.Runtime.InteropServices.Marshal.GetActiveObject
    (“Word.Application” );
    WordApplication.Visible = false;
    }
    catch
    {
    //Ignore the COMException if there is no existing WORD application running.
    }
    finally
    {
    if (WordApplication == null)
    {
    try
    {
    Type t = System.Type.GetTypeFromProgID(“Word.Application”, “localhost”);
    WordApplication = (Word.ApplicationClass)Activator.CreateInstance(t);
    WordApplication.Visible = false;
    }
    catch (Exception ex)
    {
    throw new Exception(“Create Instance failed [Word.Application].”,ex);
    }
    }
    }
    }
    else
    {
    return false;
    }
    </code>

    Prashant Nayak June 9, 2005 at 2:43 pm #
  5. I believe that code above is the best way to do this… it is the C# equivalent of the standard way I have always used to do this… try GetObject() and if it returns nothing, go with CreateObject…

    Duncan Mackenzie June 9, 2005 at 3:18 pm #
  6. i got solution for this from http://dotnetforums.com/showthread.php?t=554

    /—————————-
    The problem is that your IIS server doesn’t have the appropriate rights to launch a Microsoft Word-document DCOM object.

    First you have to find out the user or group your IIS server runs as. IIS 6 normally runs as “NT AUTHORITY\NETWORK SERVICE”. Second, you can start the tool “DCOMCNFG.EXE” (Component Services). Go to Console Root –> Component Services –> Computers –> My Computer –> DCOM Config –> Microsoft Word-document –> properties –> security –> Launch Permissions –> edit. Add the appropriate user/groep, like “NT AUTHORITY\NETWORK SERVICE”. Now it should work.
    /——————————————————-

    bipin

    bipin July 19, 2005 at 10:04 am #
  7. you folks look like you might be able to help me.

    I am trying to save a text document as a word document. All goes well except when I change the font name and/or size it shows on the open documemnt but when I save and close, it reverts to the old font. Any ideas?

    eliza September 7, 2005 at 3:13 pm #
  8. make sure it is not saved as a text file

    RB September 21, 2005 at 3:42 pm #
  9. Hey, i got a problem, when I try to open the document I noticed that the winword process is fired but I can’t see the word document opened. My code is exactly the same as the one above. any Idea?

    David Murphy March 14, 2006 at 4:06 pm #
  10. I need to save the ActiveDocument to a temporary file, similar to how Word
    saves files for auto recover. I’ve tried the SaveAs() method, but it changes
    the title bar. This also causes the next “Save” command by the user to save
    to this temporary file instead of the user’s original file. I want this save
    to be completely transparent to the user.
    One idea I’ve had is to make a copy of the Document object, however I can’t
    find any way to copy it.
    Any ideas?
    Thanks,

    Boris. April 6, 2006 at 8:40 pm #
  11. hello,
    I am getting the foolowing erron at line

    Word.ApplicationClass wordApp = new Word.ApplicationClass();

    System.Runtime.InteropServices.COMException: The message filter indicated that the application is busy.

    can you help me ?
    thanks

    Anup April 21, 2006 at 8:45 am #
  12. hey i wanted to retrieve data from MS SQL server Database and then open the MS word write the data in formated form , save the word document and email it to client .. how can this be possible by using VB.NEt .. i need code .. please its urgent help me out
    thanks in advance

    zxc April 24, 2006 at 6:35 am #
  13. Hi,

    I also looking for a code article, snnipset etc for:

    “I wanted to save & retrieve MS Word Document into/ from MS SQL server Database in VB.NET form. I do not want to open word document as usal way.

    I want to create a VB.NET form and in this form I want to be able show user the word document than they can save back into MS SQL Server or if they wish they can print.

    I search in internet and couldn’t find any answer. Am I wrong trck or seems no one going to help us.

    Thank you.

    Rgds,
    Niyazi

    Niyazi April 26, 2006 at 12:12 pm #
  14. Hi folks,

    I’m pretty new to VB.net as you will likely be able to tell by my error. I had a working application until my system crashed, I wrote it using vs.net 2003 but when I rebuilt my box I opted for VB 2005 express, now I get “type ‘Word.Application’ is not defined” in the error list. I can’t seem to find the right reference to Word to fix it. the broken bit is below, I guess I just need a nudge in the right direction on how to define an office applicaion in vb2005….I think!?!

    Private wordApp As New Word.Application()

    any help…or even just pointing and laughing would be very helpful at this point.

    Broken Coder April 28, 2006 at 2:46 pm #
  15. i m using .net 2.0 and doing automation of word in c#
    but once doc file is created i m not able to delete it .
    i have used some code given below

    finally
    {
    System.Threading.Thread.Sleep(5000);
    //RELEASE EVERY OBJECT CREATED
    Object saveChanges = false;
    Object originalFormat = Type.Missing;
    Object routeDocument = Type.Missing;

    if(dt != null)
    {
    while(System.Runtime.InteropServices.Marshal.ReleaseComObject(dt) !=0)
    System.Threading.Thread.Sleep(1000);
    dt = null;
    }
    if(rd != null)
    {
    while(System.Runtime.InteropServices.Marshal.ReleaseComObject(rd) !=0)
    System.Threading.Thread.Sleep(1000);
    rd = null;
    }
    if(oDocs != null)
    {
    ((Word._Document)oDocs).Close(ref saveChanges, ref originalFormat, ref routeDocument);
    while(System.Runtime.InteropServices.Marshal.ReleaseComObject(oDocs) !=0)
    System.Threading.Thread.Sleep(1000);
    oDocs = null;
    }

    if(oWord != null)
    {
    oWord.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
    while(System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord) !=0)
    System.Threading.Thread.Sleep(1000);
    oWord = null;
    }
    }

    but this code is not able to destroy com
    the same code is working fine in .net 1.1

    gaurav tyagi May 8, 2006 at 12:46 pm #
  16. I would like to save word document into table of sql server as it is (with available formatting in word document like bold, hyperlink, book mark etc). After that I would like to retrieve / read doucments from table of sql server.

    My mail id is padam_india@yahoo.com, Kindly help me on this.

    Padam Kumar Tripathi May 23, 2006 at 7:37 am #
  17. i have a different problem :

    When I do the following, it raises an exception says : specified cast is invalid

    ApplicationClass word_ = null;
    word_=(Word.ApplicationClass)System.Runtime.InteropServices.Marshal.GetActiveObject(“Word.Application” );

    when i do :
    Type t = System.Type.GetTypeFromProgID(“Word.Application”,”localhost”);
    word_ = (Word.ApplicationClass)Activator.CreateInstance(t);

    it gives me the same error message

    I have two version of the MS-Word, word 2000 and word 2003, and i can see word 2000 is registered in my ROT table when i run the above code

    Does anyone know how to solve this ? big thanks !!

    Alex May 25, 2006 at 6:54 pm #
  18. I hve problem with opening a existing word file using vb.net.

    i.e. i shall be able to open a word file from hard disk and file should be shown on screen in word program.

    can u plz help me???!!!

    thnks

    Parmar Amit June 21, 2006 at 8:25 pm #
  19. For Parmar Amit & David Murphey:

    If you want to make the word application visible to the user then change the following line in the code above:

    WordApplication.Visible = false;

    to

    WordApplication.Visible = true;

    Derek July 21, 2006 at 1:30 pm #
  20. hi,

    i’m using c# to open word template and fill it’s field with some data. this work fine in my PC, but when I trie dto access it from other Pc in the network word application doesn’t show and nothing happen

    it seems that this way doesn’t work in client side ? Any Ideas??!

    emotions July 26, 2006 at 5:26 am #
  21. hey m creating a report using different schema’s
    i want to export it to word but with header footer and pagebreaks as data is coming from database and is dynamic.
    wat to do.
    right now i m trying to use word object in vb.net but is is giving me error access denied in line where m creating a new word application.

    Plz help i have to release my system.

    komila August 2, 2006 at 9:14 am #
  22. I post my comment and seems noone trying to help, like I ask them to write the code for me. I came to post hear because my firends suggested to me but seems there is no luck.

    So what am I missing, in this blog to learn or at least get some answer negative or postive?

    Thank you,
    Rgds,
    Niyazi

    Niyazi August 15, 2006 at 4:12 pm #
  23. Niyazi, put an email address into the URL and I’ll get back to you

    Duncan Mackenzie August 15, 2006 at 4:20 pm #
  24. I want to read a Section Number in Word Document. for Ex,
    5.6.4.2 Heading
    i am able to read the heading part(Heading),but the section part not able to read.
    could u please anyone help me.
    Thanx
    praba

    praba October 12, 2006 at 9:24 am #
  25. i’d found solution to part of my problem. i’m using seagate crystal report 8 to design some certificates and VB.net for my project.
    my problem now is to connect the report with the code. i’m not using report in .net studio
    i need it urengtly

    bukkie October 26, 2006 at 2:56 pm #
  26. same problem occur for me also where Niyazi told.Plz if anyone found send me code articles.

    Thanks and Regards
    ferozkhan

    ferozkhan November 2, 2006 at 12:10 pm #
  27. How many Characters does Range object accept in word document.I am trying to search for a string in the word document which is more than 256 characters And Range Object gives me error ‘String Format too Long’.Help needed.

    kkmar November 6, 2006 at 5:41 pm #
  28. Hi,
    I am trying to convert word document formatted contents to HTML. Can u please help me to do this using Interop.Word.dll…..

    And also Is there any method to read word document line by line with out loosing the formatted tags?

    One more question, how do i convert HTML string to word format other than using SaveAs?
    hope u can give some tips on this…

    Anas December 18, 2006 at 3:02 am #
  29. how can i automate the word COM component and suppress the print dialog box and deploy the application and not have the COM component try to create the registry on the server?

    Michael May 22, 2007 at 8:26 pm #

Leave a Reply