C#从SqlServer数据库读写文件源码

如下的资料是关于C#从SqlServer数据库读写文件的内容,希望能对码农们有一些用。

<%@ Page Language="C#" %>






















<%@ WebHandler Language="C#" Class="Download" %>
using System;
using System.Web;
using System.Data.SqlClient;
public class Download : IHttpHandler
{
private string connectionString = "Data Source=192.168.3.1;Initial Catalog=TestData;User Id=sa;Password=lambada;";
public void ProcessRequest(HttpContext context)
{
String fileId = context.Request.QueryString["FileId"];
if (String.IsNullOrEmpty(fileId))
{
context.Response.ContentType = "text/html";
context.Response.Write("无效的ID。");
return;
}
int id = 0;
if (!Int32.TryParse(fileId, out id))
{
context.Response.ContentType = "text/html";
context.Response.Write("ID 不是数字。");
return;
}

SqlConnection myConnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(strSql, myConnection);
command.Parameters.AddWithValue("@FileId", fileId);
myConnection.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{
String fileName = dr["Title"].ToString();
if (context.Request.UserAgent.IndexOf("MSIE") > -1)
{
fileName = HttpUtility.UrlEncode(fileName);
}
context.Response.ClearContent();
context.Response.ContentType = dr["ContentType"].ToString();
context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
context.Response.BinaryWrite((Byte[])dr["Content"]);
}
else
{
context.Response.ContentType = "text/html";
context.Response.Write("没找到文件。");
}
myConnection.Close();
myConnection.Dispose();
}

public bool IsReusable
{
get
{
return false;
}
}

}





转载于:https://www.cnblogs.com/51jiaoshou/p/10254346.html

你可能感兴趣的:(C#从SqlServer数据库读写文件源码)