【发布时间】:2016-06-19 19:39:21
【问题描述】:
当我们使用连接字符串NullReferenceException 创建连接时,发生了。错误是
用户代码未处理 NullReferenceException。
我的代码如下:
protected void upload_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using(BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr =ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles values(@Name, @ContentType, @Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", filename);
cmd.Parameters.AddWithValue("@contentType", contentType);
cmd.Parameters.AddWithValue("Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
【问题讨论】:
-
异常来自哪一行?你检查 FileUpload1.PostedFile 是否为空?
-
您能否检查一下您的 app.config/web.config 文件中是否确实定义了带有键
constr的连接字符串?
标签: c# sql asp.net nullreferenceexception