user2911539 user2911539 - 1 year ago 95
ASP.NET (C#) Question

Storing Images in Project Folder - Directory Not Found Error Message

I am trying to save images to a SlideImages folder in my ASP.NET web forms website, using C#.

When I try to submit an image using the following code:

protected void btnSubmitImage_Click(object sender, EventArgs e)
//Get Filename from fileupload control
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
//Save images into SlideImages folder
fileuploadimages.SaveAs(Server.MapPath("SlideImages/" + filename));

//Open the database connection
//Query to insert images name and Description into database
SqlCommand cmd = new SqlCommand("Insert into SlideShowTable(ImageName,Description) values(@ImageName,@Description)", con7);
//Passing parameters to query

cmd.Parameters.AddWithValue("@ImageName", filename);
cmd.Parameters.AddWithValue("@Description", txtDesc.Text);
//Close dbconnection
txtDesc.Text = string.Empty;

I get the below error message when trying to execute the 4th line of the code above.

An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code. Additional information: Could not find a part of the path 'C:\Users\11342\OneDrive\Documents\4th Year\FYP\BallinoraWaterfallCommunity\SlideImages\'.

Here is my project folder structure. I am trying to store the images in the SlideImages folder of my project.

I managed to successfully store images in the 'Images' folder using the below code. I have tried to adapt it to fix the above problem, but I have not been able to.

protected void btnSubmit_Click(object sender, EventArgs e)
//Get Filename from fileupload control
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
//Save images into Images folder
fileuploadimages.SaveAs(Server.MapPath("Images/" + filename));
//Getting dbconnection from web.config connectionstring
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BallinoraDBConnectionString1"].ToString());
//Open the database connection
//Query to insert images path and name into database
SqlCommand cmd = new SqlCommand("Insert into Group_Images(ImageName,ImagePath) values(@ImageName,@ImagePath)", con);
//Passing parameters to query
cmd.Parameters.AddWithValue("@ImageName", filename);
cmd.Parameters.AddWithValue("@ImagePath", "Images/" + filename);
//Close dbconnection

Answer Source

You should use Server.MapPath("~/SlideImages). Notice the ~/ prefix which forces the mappath to start at the root of the web application.

Then add the file name as the file does not exist yet on disk but you should use System.IO.Path.Combine to combine the mapped root website path (and images folder) with the file name.

Also you should check if the directory exists or not. In your screen shot you have content in Images so this folder is probably being copied to your destination website path when you deploy. The other one is empty, it might not be created when you deploy your application because there is no content to copy.

Here is the modified code, check if it exists and create it if it does not. You should verify the web application's user context has sufficient privileges to create a directory in the root website directory.

var directory = Server.MapPath("~/SlideImages");

fileuploadimages.SaveAs(System.IO.Path.Combine(directory, filename));

Side note

You should wrap any instances that implement IDisposable with using blocks or make sure that they are disposed of in the dispose method of the containing type. I noticed in your 2nd example you created a SqlConnection instance and then called close later which is not good practice. Why that is is because if you have an Exception that occurs your SqlConnection, SqlCommand, or anything else that needs to clean up resources will stick around longer than needed which can cause issues later on like exceeding the max number of simultaneous allowed open connections to a Sql Server or not being able to serve an image because there is a lock on the file.

For more information see Best Practices - Executing Sql Statements

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download