2012-11-12 118 views
1

我嘗試了使用下面的代碼,但它引發了一個異常。 "Exception has been thrown by the target of an invocation."如何在C#中使用CreateObject打開Word文檔?

System.Type wordType = System.Type.GetTypeFromProgID("Word.Application"); 
     Object word = System.Activator.CreateInstance(wordType); 
     wordType.InvokeMember("Visible", BindingFlags.SetProperty, null, word, new Object[] { true }); 
     Object documents = wordType.InvokeMember("Documents", BindingFlags.GetProperty, null, word, null); 
     object nullobj = Missing.Value; 
     string fileName=System.AppDomain.CurrentDomain.BaseDirectory + "assets\\sample_doc.docx"; 
     object[] args = new object[15] { fileName, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, nullobj}; 
     Object document = documents.GetType().InvokeMember("Open", BindingFlags.InvokeMethod, null, documents,args);` 
+0

什麼是'documents'? – gdoron

+0

什麼版本。你使用的NET。 –

+0

嗨,我已經更新了我的問題,請參閱完整的代碼。謝謝。 – WangHongjian

回答

1
using (FileStream stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
{ 
Document Doc = new Document(stream); 
} 
0
public void openWordDocument(string filePath) 
{ 
    object missing = System.Reflection.Missing.Value; 

    //create a document in this path 
    object fileName = filePath; 

    object wordApp = Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application")); 
    //Setup our Word.Document 
    object wordDoc = wordApp.GetType().InvokeMember("Documents", System.Reflection.BindingFlags.GetProperty, null, wordApp, null); 
    //Set Word to be not visible 
    wordApp.GetType().InvokeMember("Visible", System.Reflection.BindingFlags.SetProperty, null, wordApp, new object[] { true }); 

    //Open the word document fileName 
    object activeDoc = wordDoc.GetType().InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, wordDoc, new Object[] { fileName }); 
} 
+0

我的意思是,我必須使用這樣的代碼來做到這一點。 System.Type wordType = System.Type.GetTypeFromProgID(「Word.Application」); Object word = System.Activator.CreateInstance(wordType); – WangHongjian

+0

查看我編輯的代碼。希望它的幫助。 –

+0

謝謝,它的工作原理。 :D – WangHongjian