C# c中的用户代码未处理NullReferenceException#
当我们使用连接字符串创建连接时,会发生异常。错误是 用户代码未处理NullReferenceException 我的代码如下:C# c中的用户代码未处理NullReferenceException#,c#,sql,asp.net,nullreferenceexception,C#,Sql,Asp.net,Nullreferenceexception,当我们使用连接字符串创建连接时,会发生异常。错误是 用户代码未处理NullReferenceException 我的代码如下: protected void upload_Click(object sender, EventArgs e) { string filename = Path.GetFileName(FileUpload1.PostedFile.FileName); string contentType = FileUpload1.Pos
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);
}
您使用的是数据,而不是中的@Data cmd.Parameters.AddWithValue(“数据”,字节) 所以这是正确的发送方式 cmd.Parameters.AddWithValue(“@Data”,字节)
仅发送变量数据时,您正在使用@Data变量将值插入表中
cmd.Parameters.AddWithValue("Data", bytes); // error prompt code
cmd.Parameters.AddWithValue("@Data", bytes); // correct Code
最有可能是因为FileUpload1.PostedFile为null而引发NullReferenceException的代码
您可能在UpdatePanel中添加了文件上载。如果是,则需要使用PostBackTrigger。异常来自哪一行?您是否检查了FileUpload1.PostedFile是否为空?是否可以检查您的app.config/web.config文件中是否实际定义了键为
constr
的连接字符串?在提供Sql参数时,Sql参数在没有@symbol的情况下运行良好。