ASP.NET User Control for Uploading Files to your server. 
   Written By Amos Zoellner        Main Page

Abstract:

Many times a web application requires files to be uploaded to the server, which can then be accessed either by the System.IO methods, or by manual review later.
This user control creates a simple interface for managing uploaded content by providing support for the file naming and managing, as well as screen for certain file types, size, etc.



The user control creates the following simple interface. (Modify as you wish)



Properties/Methods:


.aspx code for the Web Page with the FileControl on it:
MyPage.aspx
file control register:
		
<%@ Register TagPrefix="Ctrl" TagName="FileControl" Src="FileControl.ascx" %>

form tag: Note the ENCTYPE value, which is required for uploading to occur!

file control tag: codebehind: public FileControl MyFileControl; Page_Load: MyFileControl.PROPERTY = VALUE; (Set as many or few properties as you need.)



.ascx code for the File Control:
FileControl.ascx
<%@ Control Language="c#" AutoEventWireup="false" Codebehind="FileControl.ascx.cs" Inherits="PROJECT.UserControls.FileControl" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
Select file for upload:




.cs code for the codebehind:
FileControl.ascx.cs

namespace PROJECT.UserControls
{
	using System;
	using System.Collections;
	using System.ComponentModel;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.SessionState;
	using System.Web.UI;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
	using System.IO;

	
	/// 
	///		User Control that handles uploads.
	///		User Control uploads file, attaches 'Prefix' to its name, and saves to 'Folder'
	///		For file uploading to be enabled on .aspx pages, the Form tag must include:
	///		enctype="multipart/form-data"
	///		
	public abstract class FileControl : System.Web.UI.UserControl
	{

		protected System.Web.UI.HtmlControls.HtmlInputFile txtFile;
		protected System.Web.UI.WebControls.Label txtMessage;
		protected System.Web.UI.WebControls.Button FileButton;
		protected System.Web.UI.WebControls.Label _Prefix;
		protected System.Web.UI.WebControls.Label _Folder;
		protected System.Web.UI.WebControls.Label _MaxLength;
		protected System.Web.UI.WebControls.Label _Type;
		protected System.Web.UI.WebControls.Label _FileName;

		/// 
		/// initialize variables: allow only uploads less than 100KB, default to wwwroot folder and no prefix, allow text based files only
		/// 
		/// 
		/// 
		private void Page_Load(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				Folder = "";
				Prefix = "";
				MaxLength = 100;
				Type = "text";
				FileName = "";

			}
			txtMessage.Text = "";
			
			
		}	// method Page_Load


		/// 
		/// Prefix attatched to begininning of a filename before saving to server (a unique ID, for example).
		/// If not given, defaults to empty string.
		/// 
		public string Prefix
		{
			get { return _Prefix.Text; }
			set { _Prefix.Text = value; } 
		}	// prefix
		
		/// 
		/// Folder name within current directory where file will be stored.
		/// If not given, defaults to wwwroot
                /// If folder does not exist on server, it is created.
		/// 
		public string Folder
		{
			get { 
                            if (!System.IO.Directory.Exists(Server.MapPath(value)))
				System.IO.Directory.CreateDirectory(Server.MapPath(value));
                            return _Folder.Text; 
                            } 
			set { _Folder.Text = value; }
		}	// folder

		/// 
		/// FileName to save file as in upload directory.
		/// If not given, defaults to file name of uploaded file.
		/// If a prefix is specified, it will be appended to the beginning of this filename.
		/// 
		public string FileName
		{
			get { return _FileName.Text; } 
			set { _FileName.Text = value; }
		}	// filename

		/// 
		/// Maximum length in Kilobytes of file to upload.
		/// If not given, defaults to 100.
		/// 
		public int MaxLength
		{
			get { 
				if (_MaxLength.Text !="")
					return Int32.Parse(_MaxLength.Text);
				else return 0;
			} 
			set { _MaxLength.Text = value.ToString(); }
		}	// maxlength

		/// 
		/// Setting this to 'text' will allow only Text based files, webpages PDF files, and Word documents to be uploaded.
		/// Setting this to 'text/image' will allow most image and text based files to be uploaded.
		/// Otherwise, set this to a comma delimited list of allowable extensions. ".doc, .wps" for example.
		/// 
		public string Type
		{
			get { return _Type.Text; } 
			set { _Type.Text = value; }
		}	// type



		/// 
		/// Upload file to server
		/// 
		/// 
		/// 
		protected void Upload(object o, EventArgs e)
		{
			try
			{ 
				string strFolderName = Folder;
				string strFileName = txtFile.PostedFile.FileName;
		
				strFileName = Prefix + strFileName.Substring(strFileName.LastIndexOf("\")+1);
				if (FileName != "")
					strFileName = Prefix + FileName + strFileName.Substring(strFileName.LastIndexOf("."));
				string type = txtFile.PostedFile.ContentType;
				int length = txtFile.PostedFile.ContentLength;
				
				try 
				{
					if (length > MaxLength * 1000)
					{
						throw new System.Exception("File must be < " + (MaxLength * 1000) + " bytes in size.  File Size:" + length.ToString());
					}
					if (Type == "text" && !(type.StartsWith("text/") || type == "application/msword" || type == "application/pdf"))
					{
						throw new System.Exception("File Type must be either text based or MSWord. Type: " + type);
					}
					if (Type == "text/image" && !(type.StartsWith("text/") || type == "application/pdf" || type == "application/msword" || type.StartsWith("image/")))
					{
						throw new System.Exception("File Type must be either text based, an image, PDF, or MSWord. Type: " + type);
					}
					if (Type != "text" && Type != "text/image" && Type.IndexOf(strFileName.Substring(strFileName.LastIndexOf("."))) < 0)
					{
						throw new System.Exception("This File type not accepted. Type: " + strFileName.Substring(strFileName.LastIndexOf(".")));
					}
					
						txtFile.PostedFile.SaveAs(Server.MapPath(strFolderName + "\"+strFileName));
					
						txtMessage.Text="Uploaded successfully: " + txtFile.PostedFile.FileName +"
"; } catch (Exception err) { txtMessage.Text = " Error Uploading " + txtFile.PostedFile.FileName +"
" + err.Message + "
If problems persist, ensure file is saved and not in use or open.
"; } } catch { // not valid txtMessage.Text = "File name invalid."; } } // method Upload #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } // OnInit /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } // InitializeComponent #endregion } // class } // namespace