繁体   English   中英

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

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

我正在尝试将PDF文件保存到SQL Server,我已经有一个生成PDF的方法,但是打开一个显示该文件的窗口。

但是,现在我必须生成PDF,但必须将其保存到图像字段中的数据库中。

我必须从MemoryStream对象中保存这个文件,我准备保存,显示等。

我有这个:

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

我正在googling aroung,我想我必须将这个MemoryStream转换为FileStream,所以我可以将它保存到DB,但我不知道如何。

谢谢!!

为什么首先要将其保存到文件中以便将其保存到数据库中?

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