當我們使用連接字符串創建連接NullReferenceException
發生時。錯誤是NullReferenceException由用戶代碼在c中未處理#
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是否爲空? – Patrick
你能否檢查一下連接字符串是否帶有'constr'鍵實際上是在你的app.config/web.config文件中定義的? – RBT