2012-07-12 42 views
3

我要保存在數據庫中一個Word文檔,我這樣做,以這種方式:如何將字節[]轉換爲互操作對象的Word(轉換爲word文檔)?

FileStream st = new FileStream(filePath, FileMode.Open); 
    byte[] buffer = new byte[st.Length]; 
    st.Read(buffer, 0, (int)st.Length); 
    st.Close(); 
    //save Buffer into DB 
    //myentityobject.FileContent = buffer; 
    //save it 

,但是當我想讀它,我不如何使從流word文檔,我從DB.i嘗試這樣的事情:

var doc = myentityobject.FileContent; 
MemoryStream stream = new MemoryStream(doc as byte[]); 
letterPatternDoc = new Document(stream); 
filePath = @"D:\LetterPatternDocument001.doc"; 
object oMissing = System.Reflection.Missing.Value; 
currentApp = new wd.Application(); 
currentApp.Visible = true; 
currentDoc = currentApp.Documents.Add(Type.Missing, Type.Missing); 
currentDoc = doc; 
currentDoc.SaveAs(ref path, oMissing, oMissing, oMissing, oMissing, oMissing, false 
       , oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,  oMissing, oMissing); 

但它沒有工作。

編輯:

我改變代碼,它工作的,現在,我通過文件流保存文件,然後讀取它。但是我不知道這是一個好的解決方案嗎?

FileStream fileSream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite); 
     BinaryWriter bw = new BinaryWriter(fileSream); 
     bw.Write(FileContent);//filecontent is a byte[] 
     fileSream.Close(); 

     // WordDoc.OpenDocument(filePath); 
+0

詳細說明「不起作用」......它做什麼(或不做) – psubsee2003 2012-07-12 05:27:10

+0

@ psubsee2003:正如我所說的,我在數據庫中保存了一個word文檔,現在我想閱讀並在word應用程序中顯示它。 – 2012-07-12 05:39:57

+0

什麼是bw.Write(ViewSource.CurrentItem.LetterPatternDocument.FileContent); 那是你自己的觀衆嗎? – JohnZaj 2012-07-12 12:07:32

回答

0

你可以試試這個方法: 將文件保存到某個地方,並保存文件路徑database.when要讀取這個文件,你可以從database.hope的文件路徑,它可以幫助你:)

0

嘗試序列化文檔對象,從而保存文檔的狀態並將其保存在數據庫中。閱讀反序列化文檔對象時將再次提供給您顯示。

0

字是不能夠打開一個流,但你可以保存它,修改它,然後在數據庫中更新後,只要刪除這個「臨時」文件

0

如果你不想使用FileStream您還可以利用System.IO.File名稱空間內的靜態方法內置的WriteAllBytes

下面是一個簡單的例子(假設Interop.Word安裝和參考):關於這個話題,你也可以read this post

// byte[] fileBytes = getFileBytesFromDB(); 
var tmpFile = Path.GetTempFileName(); 
File.WriteAllBytes(tmpFile, fileBytes); 

Application app = new word.Application(); 
Document doc = app.Documents.Open(filePath); 

// do your stuff  

// convert the DOCX file back to a Byte Array 
doc.Close(); 
app.Quit(); // VERY IMPORTANT: do this to close the MS Word instance 
byte[] newFileBytes= File.ReadAllBytes(tmpFile); 
File.Delete(tmpFile); 

瞭解更多信息。