简体   繁体   English

C#3.0 - 如何从MemoryStream将文件保存到数据库?

[英]C# 3.0 - How can I save a file to database from a MemoryStream?

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. 我正在尝试将PDF文件保存到SQL Server,我已经有一个生成PDF的方法,但是打开一个显示该文件的窗口。

But, now I have to generate a PDF, but it must be saved to database in a image field. 但是,现在我必须生成PDF,但必须将其保存到图像字段中的数据库中。

And I have to save this file from a MemoryStream object that I get ready to be saved, showed etc. 我必须从MemoryStream对象中保存这个文件,我准备保存,显示等。

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. 我正在googling aroung,我想我必须将这个MemoryStream转换为FileStream,所以我可以将它保存到DB,但我不知道如何。

Thanks!! 谢谢!!

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 . 如果你这样做,最好的方法可能是使用MemoryStream.WriteTo ,传入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. 但是,如果您只需要将数据作为字节数组来写入数据库,则可以使用ToArray方法。

(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.) (将数据写入数据库的确切方式将取决于您一般如何访问数据库。如果您告诉我们更多相关信息,我们可能会提供更具体的建议。)

Here's an example method. 这是一个示例方法。 You pass the document as a Byte Array using memorystream.ToArray(). 使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM