Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Open Word Document Located in the Computer in C#

I'm using WinForms. I have a form that has a button.

Goal: On button click: Open up a word document. Where the file path is hard coded into the program. I don't want the users to have to locate the word document.

Problem: I receive this error message. When I wrote my code, I get a red error line under 'Application'.

enter image description here

    private void button1_Click(object sender, EventArgs e)
    { 
        this.Application.Documents.Open(@"C:\Test\NewDocument.docx", ReadOnly:true)

    }
like image 944
taji01 Avatar asked Sep 28 '15 05:09

taji01


People also ask

How do I find where a Word document is open?

Under “Computer” on the right side of the backstage screen, either select the “Current Folder,” a folder under “Recent Folders,” or click the “Browse” button at the bottom of the list. The path to the location of the currently open file displays in the address bar at the top of the “Save As” dialog box.


2 Answers

Instead of adding interop in your reference, you may also consider to use this:

System.Diagnostics.Process.Start(@"C:\Test\NewDocument.docx");
like image 191
Heisenberg Avatar answered Sep 23 '22 05:09

Heisenberg


first add the dll of Microsoft.Office.Interop.Word to your references then add this:

using Microsoft.Office.Interop.Word;

and use the following code:

Application ap = new Application(); 
Document document = ap.Documents.Open(@"C:\Test\NewDocument.docx");
like image 42
amit dayama Avatar answered Sep 22 '22 05:09

amit dayama