The FileUpload control enables users to upload files to your web application. After the file is uploaded, you can store the file anywhere you please. Normally, you store the file either on the disk or in a database. This article explains first option that is how to store the file in selected folder on the disk by using FileUpload control.
Create an asp.net web site, and then add below code for both .aspx file and .aspx.cs file.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>FileUpload Control in ASP.NET</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label id="lblFile" Text="File To Upload:" Runat="server" />
<asp:FileUpload id="fu1" Runat="server" /><br /><br />
<asp:Button id="btnSave" Text="Save File" OnClick="btnSave_Click" Runat="server" />
</div>
</form>
</body>
</html>
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (fu1.HasFile)
{
String filePath = "~/UploadedFiles/" + fu1.FileName;
fu1.SaveAs(MapPath(filePath));
}
}
}
Here we have one label control, fileupload control and button control. By using FileUpload control we are able to browse the files and on button click we are saving the selected file in UploadFiles folder. Before saving file, we are checking whether user selecting the file or not by using HasFile property of FileUpload control.
To save a file to the file system, the Windows account associated with the ASP.NET page must have sufficient permissions to save the file. For Windows 2003 Servers, an ASP.NET page executes in the security context of the NETWORK SERVICE account. In the case of every other operating system, an ASP.NET page executes in the security context of the ASPNET account.
To enable the ASP.NET framework to save an uploaded file to a particular folder, you need to right-click the folder within Windows Explorer, select the Security tab, and provide either the NETWORK SERVICE or ASPNET account Write permissions for the folder(here UploadFiles folder) .