Click here to Skip to main content
15,898,708 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I get "Object reference not set to an instance of an object" - during FileUpload1. I know the issue is null value in fileuplod1. But if I run the same code on another project then it is working fine. But when I run this code on my actual project it gets error "Object reference not set to an instance of an object".

Please help some...

What I have tried:

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["ConnectionString"].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();
}
}
}
BindGrid();
}
Response.Redirect(Request.Url.AbsoluteUri);
}
Posted
Updated 4-Oct-16 19:18pm
Comments
Karthik_Mahalingam 5-Oct-16 0:57am    
which line?
Member 12245539 5-Oct-16 0:58am    
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
Karthik_Mahalingam 5-Oct-16 0:59am    
is the file selected in the control?
Member 12245539 5-Oct-16 1:03am    
No file I have to select.......
Karthik_Mahalingam 5-Oct-16 1:09am    
then how will you upload the file?

Check the File in the control before doing postback/upload button click
C#
if (FileUpload1.HasFile)
{
    // your code
}
 
Share this answer
 
add try / catch with exception and get stack trace to debug.
 
Share this answer
 
Comments
Member 12245539 5-Oct-16 1:35am    
Sir I tried this but nothing happens....
Member 12245539 5-Oct-16 1:35am    
compiler jumps from
if (FileUpload1.HasFile) to end of closeline "}"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900