An ASP.NET 2.0 Script To Share Files Among Users

Recently asked on Yahoo! Answers:

How could I enable user to upload and download file from server using 2?

How could I enable a user to upload file to the server and then view link to download this file from the server to anthor user i when he enters the site using ASP.NET 2?

The problems here could be handled very easily simply by using the built-in FileUpload class and the DirectoryInfo / FileInfo classes to display the files in the targeted directory.

So, let’s run that simple code today.

Web.config Settings

We’ll set a few application variables in the web.config file to make our application very portable. We need to record:

  • The URI (that is, the physical path) to the file
  • The URL (that is, the hyperlink) to the file
  • We’ll also add the System.IO namespace to the namespaces
	<add key="UploadBaseURI" value="c:physicalpathtoyouruploaddirectory" />
	<add key="UploadBaseURL" value="http/path/to/your/upload/directory/"/>
	<add namespace="System.IO"/>

<h3>The HTML Form</h3>

With the keys and namespaces added, we can move on to the HTML.

	<li>We need the FileUpload control, as well as a RequiredFieldValidator to make sure that if someone uploads a file, they've entered something in the control.</li>
	<li>We need a button to submit the form.</li>
	<li>Finally, we have a div that we will programmatically update with the available file list.</li>

<html xmlns="" >
	<head runat="server">
		<title>Simple File Upload</title>
		<form id="form1" runat="server">
			<h1>Uploaded Files</h1>
			<div runat="server" id="divFiles"></div>
			<br />
			<h2>Upload Your File</h2>
			<asp:Label runat="server" ID="lblStatus" />
					<td>File To Upload:</td>
					<td><asp:FileUpload runat="server" ID="fuMain" /></td>
					<td><asp:RequiredFieldValidator runat="server" ID="rfvFU" ControlToValidate="fuMain" ErrorMessage="Please provide a file to upload" Display="Dynamic" /></td>
			<br />
			<asp:Button runat="server" ID="btnSubmit" Text="Upload File" OnClick="btnSubmit_onClick" />

With the HTML out of the way, we need three subroutines:

  • A Page_Load subroutine that will show all users the file list upon first visiting the page.
  • A subroutine to show us the files
  • A subroutine to upload user files, then refresh the file list

The Page_Load Subroutine

It doesn’t get more rudimentary than this: Check for page postback; if the page isn’t posting back, show the list of files.

Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs)
	If Not Page.IsPostBack Then
		'as the name says, show files
	End If
End Sub

The ShowAvailableFiles Subroutine

Showing the files is fairly straightforward.

  • We create an HTML table
  • We open the directory up with DirectoryInfo, then get all the files from it
  • We load those files into an array of FileInfo objects
  • We check the length of the array. If it’s 0, we know there are no files. If it’s longer, we know there are files to display.
  • We iterate through the FileInfo array we created, constructing URLs for each file and showing its upload (LastWriteTime) time.
  • We finish the HTML table, and then assign the table to the display DIV’s InnerHtml
Sub ShowAvailableFiles()
	'display all available files in a table
	Dim strOut As String, strPath As String, strBase As String = ConfigurationManager.AppSettings("UploadBaseURL").ToString()

	'start building the table
	strOut = "<table>"
	strOut += "<tr><th>File</th><th>Date / Time Uploaded</th></tr>"

	'get all the files in our upload directory
	'load into an array of FileInfo objects
	Dim objDir As New DirectoryInfo(ConfigurationManager.AppSettings("UploadBaseURI").ToString())
	Dim objFiles() As FileInfo = objDir.GetFiles()
	Dim objFile As FileInfo

	'if we have no files, put message out
	If objFiles.Length = 0 Then
		strOut += "<tr><td colspan=""2"">No files</td></tr>"
		For Each objFile In objFiles
			'provide a link to each file, as well as its upload date / time
			'(LastWriteTime is the proper use here; CreateTime may be the
			'date the file was made, not the date it was uploaded
			strPath = strBase + objFile.Name
			strOut += "<tr><td><a href=""" + strPath + """>" + objFile.Name + "</a></td>"
			strOut += "<td>" + String.Format("{0:F}", objFile.LastWriteTime) + "</td></tr>"
	End If

	'close the table, set the HTML for the DIV to show the listing
	strOut += "</table>"
	divFiles.InnerHtml = strOut
End Sub

The btnSubmit_onClick Subroutine

The last task is the subroutine that handles file uploading.

  • It checks if there was a file sent via the FileUpload control
  • If so, it tries to save the uploaded file to the URI for our uploaded files
  • If the file upload was bad, an error message is output
  • The available file list is refreshed
Sub btnSubmit_onClick(ByVal Sender As Object, ByVal E As EventArgs)
	'check for good file
	If fuMain.HasFile() Then
		'set upload path string from app key
		Dim strPath As String = ConfigurationManager.AppSettings("UploadBaseURI").ToString() + fuMain.FileName
		'if we have a good upload, tell user;
		'otherwise, tell user the problem
		Catch ex As Exception
			lblStatus.Text = "Error trying to save the file you uploaded: " + ex.Message
			'no matter what, refresh the file list
		End Try
		'warn that no file was sent to server
		lblStatus.Text = "No file was uploaded. Please try again."
	End If

Final Notes

There are all kinds of security holes in this code. Ideally, you should never place a writable directory in your public HTML path, nor should you allow people to upload any old thing they want. If you use this as is, someone could upload a malicious page to your Web site and do all sorts of damage with it; they could distribute illegal materials via your site; the list of potential mischief is endless.

As the license states, this code is provided as-is with no warranty whatsoever.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Check out the Commenting Guidelines before commenting, please!
  • Want to share code? Please put it into a GitHub Gist, CodePen or pastebin and link to that in your comment.
  • Just have a line or two of markup? Wrap them in an appropriate SyntaxHighlighter Evolved shortcode for your programming language, please!