从数据库C#打开二进制文件

Chi*_*ins 4 c# database sql-server pdf asp.net

我在SQL Server数据库中有PDF文件数据,列类型image(坏的以前的数据库设计器).我需要做的是将二进制数据读出到客户端,以便他们可以将PDF直接下载到他们的计算机上.

到目前为止,我的代码如下:

SqlConnection con = new SqlConnection();
con.ConnectionString = "casIntranetConnectionString";

SqlCommand com = new SqlCommand("SELECT [File], [FileName] FROM [com].[catalog1] WHERE [FileName] = @filename");
com.Connection = con;
com.Parameters.AddWithValue("filename", Request.QueryString["filename"]);

con.Open();

SqlDataReader reader = com.ExecuteReader();

if (reader.Read())
{
    Response.Clear();
    Response.AddHeader("Content-Type", "application/pdf");
    Response.AddHeader("Content-Disposition", "inline; filename=" + Request.QueryString["filename"] + ".pdf");
}
Run Code Online (Sandbox Code Playgroud)

我假设我需要读者读出字节,但这就是我不知道我在做什么的地方.有什么建议?

谢谢!

Ric*_*lly 5

您可以使用HttpResponse BinaryWrite方法:

var bytes = reader.GetSqlBytes(index);
Response.BinaryWrite(bytes.Value);
Run Code Online (Sandbox Code Playgroud)

顺便说一句,请考虑分离职责,您有一个负责访问数据库和写入响应的方法.这将导致将来出现维护问题.请参阅此处以获取描述SOLID原则的有用博客文章.抱歉,如果你的代码片段是人为的,但万一其他人偶然发现这个问题,我想包括一个"但不要这样做"的免责声明!