views:

1864

answers:

2

Hi everyone!

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!!

+4  A: 

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.)

Jon Skeet
Jon, Like you said, I just need to save this MemoryStream PDF file to database. If I use the byte[] myBytes = myMemory.ToArray() I will be able to save this to database?
AndreMiranda
@AndreMiranda: It will depend on what database you are using and how you are using it.
Samuel
Exactly what Samuel said. We've currently no idea what you're using to modify the database. Usually a byte array will do the trick though, e.g. specifying it as a parameter in an insert statement with a type of SqlDbType.Image.
Jon Skeet
@Samuel: I'm using SQL Server 2005 and this PDF will be saved to a image type field
AndreMiranda
I'm dropping XpsDocuments into a blob via MemoryStream.ToArray(), so this should work with PDFs just as well.
Will
+2  A: 

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
Chris Lively