Reputation: 11
The code below is supposed to open a .docx file in my windows directory but instead of opening the file it opens only the Word Application. There is no active word document inside, not even a new document. I notice that under the file tab options like "save, save as, print, Share, Export, and Close" are all grayed out and inactive.
using Microsoft.Office;
using Word = Microsoft.Office.Interop.Word;
class Program
{
static void openFile()
{
string myText = @"C:\CSharp\WordDocs\MyDoc.docx";
var wordApp = new Word.Application();
wordApp.Visible = true;
wordApp.Activate();
Word.Documents book = wordApp.Documents;
Word.Document docOpens = book.Open(myText);
}
static void Main(string[] args)
{
//Console.WriteLine("Hello World\n");
openFile();
}
}
Upvotes: 1
Views: 2958
Reputation: 1
here I'm created the WPF button event to launch the word Application Hope this will help you . please check this out
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using System.Windows;
namespace Word_Automation_WPF
{
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
}
Microsoft.Office.Interop.Word.Application wd = newMicrosoft.Office.Interop.Word.Application();
Document doc;
private void btn_LaunchWord(object sender, RoutedEventArgs e)
{
wd.Visible = true;
wd.Activate();
wd = System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application") as Microsoft.Office.Interop.Word.Application;
doc = wd.Documents.Add();
}
}
}
Upvotes: 0
Reputation: 10393
Running your code but with a path that doesn't exist does indeed opens Word Application with no document inside. But it does throw a very informative exception as follows:
System.Runtime.InteropServices.COMException: 'Sorry, we couldn't find your file. Was it moved, renamed, or deleted? (C:\Users\nonexistantuser...\Test.docx)'
You failed to mention this in your question, but you must get an exception.
So my guess is your path is incorrect.
If the path is correct, i.e. the file exists, another possible scenario is not having appropriate read permissions. In that case again it would open an empty Word Application, but that too should throw an exception albeit a different one:
System.Runtime.InteropServices.COMException: 'Word cannot open the document: user does not have access privileges (C:\Users\NS799\Desktop\Test.docx)'
So please check if the path exists and if it does, if you have appropriate permissions.
Upvotes: 1