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.

Output:

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:

<configuration>

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

<appSettings>

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

</appSettings>

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

</configuration>

 

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)

{

try

{

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: , ,

ASP.NET