Using AppSettings with FileUpload Server Control

File upload server control is use more often for uploading file on production server. It a nice and easy way to collect documents from your website users.

Today, we will leverage power of webConfig's AppSetting section. There are times when you have to hard code some folder locations like in case of a web service reference or while uploading file, the upload location so what happens if few months later for some reason you have to change the location of this upload folder or have to change the name of the folder.


In such scenarios, you have two choices:

1) Hard code location in a variable in the code behind file

2) (This is better option) hard code location in web config's appSetting section

Option 2 is better because in case you have to change the location for any reason than you can do that easy without need of redeploy of whole website.

so to do this first create a key/value pair in web config's appSetting as shown:


<!-- other settings (omitted) -->


<add key="uploadLocation" value="~/image"/>


<!-- other settings (omitted) -->



After this you can get location using key as shown: (don't forget to add using System.Web.Configuration; at the top of the code behind)


string uploadLocation= WebConfigurationManager.AppSettings["uploadLocation"];


ASPX Code for file upload:

<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:Button ID="btnUpload" runat="server" Text="Upload"

onclick="btnUpload_Click" />

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>


CS Code:

protected void btnUpload_Click(object sender, EventArgs e)


if (FileUpload1.HasFile)




string uploadLocation= WebConfigurationManager.AppSettings["uploadLocation"];

FileUpload1.SaveAs(Server.MapPath(uploadLocation + "/" + FileUpload1.FileName.Trim().ToString()));

Label1.Text = FileUpload1.FileName.ToString() + " file is loaded!";


catch (Exception ex)


Label1.Text = "Error: " + ex.Message.ToString();




Tags: , ,