2009-04-26 203 views
2

我正在嘗試將PDF文件保存到SQL Server,並且我已經有了一個生成PDF的方法,但打開了一個顯示此文件的窗口。C#3.0 - 如何將文件從MemoryStream保存到數據庫?

但是,現在我必須生成PDF,但它必須保存到圖像字段中的數據庫。

我必須拯救MemoryStream對象,我準備要保存這個文件,顯示等

我有這樣的:

MemoryStream m = PDFHelper.gereratePDF(text, title); 

我使用Google aroung,我想我有將此MemoryStream轉換爲FileStream,以便將其保存到數據庫,但我不知道如何。

謝謝!

回答

5

爲什麼需要先將它保存到文件中才能將其保存到數據庫中?

如果這樣做,最好的方法可能是使用MemoryStream.WriteTo,傳遞FileStream。但是,如果您只需要將數據作爲字節數組寫入數據庫,則可以使用ToArray方法。

(將數據寫入到數據庫將取決於你如何在一般訪問數據庫的確切方式。如果你告訴我們更多關於這一點,我們也許可以給出更具體的建議。)

+0

Jon,就像你說的,我只需要將這個MemoryStream PDF文件保存到數據庫。如果我使用byte [] myBytes = myMemory.ToArray(),我將能夠將其保存到數據庫? – AndreMiranda 2009-04-26 16:51:12

3

這裏的一個示例方法。使用memorystream.ToArray()將文檔作爲字節數組傳遞。

public static Boolean SaveDocument(Guid candidateId, String fileName, String contentType, Byte[] data) { 
    Boolean bResult = false; 

    Database db = DatabaseFactory.CreateDatabase(Databases.Hphr.ToString()); 
    using (DbCommand dbCommand = db.GetStoredProcCommand("CandidateDocumentSave")) { 
     db.AddInParameter(dbCommand, "CandidateId", DbType.Guid, candidateId); 
     db.AddInParameter(dbCommand, "FileName", DbType.String, fileName); 
     db.AddInParameter(dbCommand, "ContentType", DbType.String, contentType); 
     db.AddInParameter(dbCommand, "FileType", DbType.String, Path.GetExtension(fileName).Substring(1)); 
     db.AddInParameter(dbCommand, "Data", DbType.Binary, data); 
     db.ExecuteNonQuery(dbCommand); 
     bResult = true; 
    } // using dbCommand 
    return bResult; 
} // method::SaveDocument 
相關問題