C# 3.0 - How can I save a file to database from a MemoryStream?
-
16-09-2019 - |
Question
I'm trying to save a PDF file to SQL Server and I already have a method that generates a PDF but is opens a window showing this file.
But, now I have to generate a PDF, but it must be saved to database in a image field.
And I have to save this file from a MemoryStream object that I get ready to be saved, showed etc.
I have this:
MemoryStream m = PDFHelper.gereratePDF(text, title);
I was googling aroung and I guess I have to convert this MemoryStream to FileStream so i can save it to DB, but I don't know how.
Thanks!!
Solution
Why would you need to save it to a file first in order to save it to the database?
If you do, the best way is probably to use MemoryStream.WriteTo
, passing in the FileStream
. However, if you only need the data as a byte array in order to write to the database, you can just use the ToArray
method.
(The exact way of writing the data to the database will depend on how you're accessing the database in general. If you tell us more about that, we can probably give more specific advice.)
OTHER TIPS
Here's an example method. You pass the document as a Byte Array using 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