2015-10-16 83 views
0

我在我的項目中嵌入Word模板文件,我增加一條,作爲資源(Resources.resx - >添加資源 - >添加現有的文件),現在我想打開它喜歡的事,這如何打開嵌入式資源word文檔?

Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application(); 
Document document = application.Documents.Open(Properties.Resources.MyDoc); 

但不幸的是,Microsoft.Office.Interop.Word.Application不能用於字節數組,我無法將MyDoc設置爲它。

回答

2

Word只能打開存在於文件系統中的文件,它不能完全從內存中運行。

做這樣的事情:

String fileName = Path.GetTempFileName(); 
File.WriteAllBytes(fileName , Properties.Resources.MyDoc); 
application.Documents.Open(fileName ); 

然後當你檢測到的詞已經被關閉,刪除文件:

File.Delete(fileName); 

這可能是一個想法(因爲性能原因)嵌入Word文檔作爲嵌入式資源而不是resx文件中的Byte[]陣列,如下所示:

Assembly thisExe = System.Reflection.Assembly.GetExecutingAssembly(); 
System.IO.Stream resourceStream = thisExe.GetManifestResourceStream("MyDoc.docx"); 
// copy the stream to a new FileStream, then open Word as-before