Click here to Skip to main content
15,888,133 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I'm trying to write a piece of code to save client uploaded file to server's path.


Code is:

C#
try
{
    MessageBox.Show("POST Request!");
    HttpFileCollection uploadedFiles = HttpContext.Current.Request.Files; //I detected that the error is caused in this line. Error is: "Object reference not set to an instance of an object"

    int i = 0;
    HttpPostedFile postedFile = uploadedFiles[i];
    System.IO.Stream fs = new FileStream(RootPath, FileMode.Create);
    fs = postedFile.InputStream;
    byte[] fileData = new byte[postedFile.ContentLength];
    fs.Write(fileData, i, postedFile.ContentLength);
    postedFile.SaveAs(RootPath + "\\" + postedFile.FileName);
    MessageBox.Show("File uploaded to Server!");

    SendString("<h1>Fail edukalt &uuml;les laetud!</h1>", Client, "");

}
catch (Exception ex)
{
    SendString("<h1>Error: "+ ex .Message + ex .Source + ex .InnerException + ex .TargetSite + ex.StackTrace + ex .HelpLink  , Client, "");
}


But can someone tell me, if the rest of the code is working and how to fix this error


Thanks
Posted

1 solution

The reason why this is crapping out is one of your files being uploaded is not there. Either way without seeing more of your code i can't tell you exactly...just that the file itself is not being received. To properly get around the file upload you should do something like this

C#
HttpFileCollection uploadedFiles = HttpContext.Current.Request.Files; //I detected that the error is caused in this line. Error is: "Object reference not set to an instance of an object"

foreach(var file in uploadedFiles)
 {
	if (file != null)
	{
		if (file.ContentLength > 0)
        {
			System.IO.Stream fs = new FileStream(RootPath, FileMode.Create);
			fs = file.InputStream;
			byte[] fileData = new byte[file.ContentLength];
			fs.Write(fileData, i, file.ContentLength);
			file.SaveAs(RootPath + "\\" + file.FileName);
			MessageBox.Show("File uploaded to Server!");
		 
			SendString("<h1>Fail edukalt üles laetud!</h1>", Client, "");
		}
	}
}


This will check to m ake sure the file is not null and then also check the content length is valid so it won't explode on this line
C#
byte[] fileData = new byte[file.ContentLength];


I have no clue if the rest of your code is working as I don't have access to your hard drive/dev environment...however for the time being the snippet above would take care of your null ref exception.
 
Share this answer
 

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