How Do I Upload Files In ASP.NET 2?

Update!! 05-24-2006 - Updated the old beta code to the RTM version of ASP.NET 2.0. Also updated the downloadable source file.

Uploading files in ASP.NET is easier than ever. All you need to do is add the new <asp:FileUpload> control to your page and write a bit of code that deals with the uploaded file once the page is posted back to the server.

To test out the new file upload control, create a new page in Visual Studio 2005. You can choose between a C# or a VB.NET version of the page. I'll be using C# in this example, but the concepts easily translate to VB.NET as well. Select the option to place the code in a separate file.
Once you have created the file, drag a FileUpload control, a Button and a Label onto the page. Set the Text property of the button to Upload. Since Visual Studio 2005 now supports adding controls from the toolbox to the code view, you don't necessarily have to drag the controls to the design view anymore; you can drag them directly into code view as well, right where you want them. No more switching to design view, and no more messed up code when you return from design view!

Once the controls are in place, the code for your page should look similar to this:

<%@ Page Language="C#" AutoEventWireup="true" 
             CodeFile="Default.aspx.cs" Inherits="DefaultPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="" >
<head id="Head1" runat="server">
  <title>File Upload Demo</title>
<form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" Runat="server" />
    <asp:Button ID="Button1" Runat="server" Text="Upload" />
    <br />
    <br />
    <asp:Label ID="Label1" Runat="server" Text="Label"></asp:Label>

Next, switch to design view (Shift+F7) and double-click the button. You'll be taken to the code behind for the file. Add the following code to the Button1_Click handler that has been added for you:
protected void Button1_Click(object sender, EventArgs e)
  if (FileUpload1.HasFile)
    if (!System.IO.Directory.Exists("C:\\MyUploads"))

    FileUpload1.SaveAs("C:\\MyUploads\\" + FileUpload1.FileName);
    Label1.Text = GetFileSpecs();
When a file has been selected and the button is clicked, the code in the Button1_Click method will run. To make sure that the user selected a valid file, I used the HasFile property. When this property returns true, the code continues to check whether the target folder exists. If it doesn't, the folder is created.
The next step is to save the uploaded file to that folder using the convenient SaveAs method of the FileUpload control.

Next, add the code for the GetFileSpecs method:
private string GetFileSpecs()
  string fileSpecs = "File<br />";
  fileSpecs += "Size " + FileUpload1.PostedFile.ContentLength + "<br />";
  fileSpecs += "Type " + FileUpload1.PostedFile.ContentType + "<br />";
  fileSpecs += "Original path and name " + FileUpload1.PostedFile.FileName + "<br />";
  fileSpecs += "Name " + FileUpload1.FileName + "<br />";
  return fileSpecs;

The GetFileSpecs method is a simple helper method that displays some useful information about the upload file. The uploaded file exposes properties like the ContentType, the original path and name of the file that was uploaded.

That's really all there is to it. Save the page, and press F5 to open it in your browser. Click the Browse button, select a file and then click the Upload button.

If all went as planned, the file has been saved to C:\MyUploads with its original name. The label on your page has been updated, and is now showing the details of the file that has been uploaded.

Things To Watch Out For

The SaveAs method of the FileUpload control will overwrite existing files with the same name without warning. To prevent this from happening, be sure to generate a unique file name. One way to do this is to generate a filename from the current date and time. Alternatively, you can rename the files with a sequential number, or prefix them with a unique key, like the user's ID.

To save the files to disk, the account that the Web server is running under needs permission to write to the specified disk and folder. Be sure to check out this FAQ to find out how you can set the required security settings.

Download Files

Source Code for this Article

Where to Next?

Wonder where to go next? You can read existing comments below or you can post a comment yourself on this article .

Consider making a donation
Please consider making a donation using PayPal. Your donation helps me to pay the bills so I can keep running Imar.Spaanjaars.Com, providing fresh content as often as possible.

Feedback by Other Visitors of Imar.Spaanjaars.Com

On Monday, February 7, 2005 8:17:25 AM pandia said:

I hav .Net 2003 .... how do i do file upload in it ?

advance thanx,

On Monday, February 7, 2005 8:59:28 PM Imar Spaanjaars said:
Did you try Google? Just search for "upload files in ASP.NET" and you'll get plenty of hits....

On Tuesday, March 15, 2005 5:40:34 AM jackyhu said:
very good
On Tuesday, August 2, 2005 6:37:04 PM Ken said:
I have learned a lot from your articles. I am well experienced but have not done much ASP. I need to do something similar to this file upload but not using 2.0.
I am writing an application that requires all clients to have a type of configuration file. The web page needs to read this file from the client disk and extract information that is later use to construct ISO messages etc.

So, basically I need to read a client-side text file and have its contents available in the code-behind with no user interaction such as textbox or anything like that to select the file. The file should be read automatically.

On Tuesday, August 2, 2005 6:47:09 PM Imar Spaanjaars said:
Hi Ken,

Nothing personal, but I hope you don't find what you need.... ;-)

That would be a MAJOR security issue. If you could read the configuration file, you could also read my Word documents, spread sheets, secret password files, Windows registry and so on. Doesn't sound like a good idea to me.

Is this running in an controlled environment (e.g. an Intranet)? Then you might get away with creating a client side ActiveX Component or with client side script using the FileSystemObject. Both technologies need the security settings set to very low though.

If you read some of my articles, I am sure you also read some of the comments and my reactions to these comments: for technical questions not directly related to this article, please use a forum like and post your question there. Can you do that? And than send me the link? I can't possibly answer all technical questions I receive through this site personally.


On Wednesday, August 10, 2005 9:46:20 AM Khurram said:
Did Microsoft provide any good solution for multiple upload in 2.0 that uses only one browse and one upload button to upload multiple files in one go?

I have seen this implemented in Sharepoint portal and yahoo photos but both use ActiveX controls. i can see that there is an <Asp:Fileupload control in 2.0 which i did not try since the online sample is not good enough to convince me to spend my time on it. Has anyone tried it or  any good solution in 1.1?

On Wednesday, August 10, 2005 6:03:27 PM Imar Spaanjaars said:
Hi Khurram,

No, they didn't, because this is not something that can be fixed server side with a technology like ASP.NET.

Browsers only allow you to upload one file at the time. So, to work around that, you need something like ActiveX or another proprietary technology that runs at the client.


On Friday, January 6, 2006 10:20:16 PM Paul Reid said:
I have found a MAJOR problem with this.  I want to upload a file with a size limited by a setting in web.config.  

First, there is no MaxFileSize setting with this control.  So, people could down your server by uploading huge files.

Second, the common (but not 100% foolproof) way of handling this is to set a hidden input field named MAX_FILE_SIZE to a value of the maximum file in bytes.  If I make this field runat="server", then Microsoft happily changes the name for me to some long formulaic name that includes lots of $s.  Then, it ceases to function.  If I try to grab the value the old way using <% = maxSize %>, then the editor removes it all the time.

This is frustrating.
On Wednesday, January 11, 2006 11:50:04 AM Imar Spaanjaars said:
You *can* limit the file size, using the maxRequestLength attribute of the httpRuntime key in the web.config file.

Check out this article for more info:


On Saturday, January 21, 2006 10:55:43 AM Paul Reid said:
Yes, but there are a couple problems with that as well.

1. It limits ALL inputs in your application, including large VIEWSTATEs.  So, let's say you want to limit your input files to 50K.  You can't use it, because you will probably have VIEWSTATEs larger than 50K in your application.

2. When the input file exceeds the maxRequestLength, the page doesn't load at all.  No ability to handle any error message or present anything to the user.

So, maxRequestLength is useful for the upper limit of making sure that your site isn't overwhelmed with hacker-sized files, but using it for anything else is a bad user experience.
On Sunday, January 22, 2006 12:11:24 PM Imar Spaanjaars said:
Yeah, I agree. It's a tradeoff between security and functionality. 100K seems like a good choice then; large enough for your files (depending on your needs) and waaaaay too big for View State anyway.

Field names are indeed renamed every now and then. This all depends on the naming container the controls live in. You can still get the control's full client ID using ClientID or UniqueID.

On Thursday, April 27, 2006 2:11:24 AM Adrian Whitehead said:
I'm trying to write a website where users can upload photos to the server. From what I understand of this example the files are stored lcoally ont eh users machine. How do I set the FileUpload1.SaveAs value to a server side folder?

On Thursday, April 27, 2006 5:40:37 AM Imar Spaanjaars said:
Hi Adrian,

Maybe you misunderstood.... A FileUpload control lives at the server. So, when you call FileUpload1.SaveAs with a local path, that local path is local to your web server.

From a client perspective, the FileUpload controls sends out the necessary HTML markup (input type="file") and on post backs accepts the uploaded file which you can then save at the server.

Does this help?

On Sunday, June 18, 2006 2:11:07 PM Martin Westein said:
This is great code! What I'm searching for is a way to insert or update a record in a database with the path of the uploaded file. Can you help me with that????
On Sunday, June 18, 2006 2:15:23 PM Imar Spaanjaars said:
Hi Martin,

You may be better off posting this in a forum like That makes it easier to post code, and discuss it. If you do post there, be sure to indicate what areas you're having problems with, e.g. data access, getting the file name etc.

If you send me the link to the post, I'll take a look.

On Thursday, August 31, 2006 12:53:45 PM Gavin said:
It is good. But I wonder if you could combine 2 steps? I mean why browse and then load? If one step does all of these, it is even better.

Could you do that?


On Thursday, August 31, 2006 12:59:39 PM Imar Spaanjaars said:
Hi Gavin,

I am not sure I understand what you mean. What do you mean with "why browse and then load"?

On Friday, September 8, 2006 10:15:57 AM Payal said:
The file upload has really become easier with the above code.
With reference to this code, is there actually no way to check the file size on client side ? The ActiveXObject("Scripting.FileSystemObject") is probably an IE only feature, it doesn't work in firefox, opera and netscape. So its of little use.

Can file size validation be achieved using Ajax ?

On Friday, September 15, 2006 2:25:02 PM Imar Spaanjaars said:
Hi Payal,

I don't think so. You'll need something like ActiveX or other browser specific technology to measure the file size at the client. For AJAX to work, you still need to upload the file to the server.

There are commercial, third party solutions available that allow you to measure the file size at the client. I think they all use Java or ActiveX to make this possible.


On Wednesday, December 27, 2006 6:03:44 PM Michael Lasell said:
Can you provide code to fire a javascript confirm if the filename is the same as one pre-existing on the server - so a yes overwrites the file and a no aborts the filesave?
On Wednesday, December 27, 2006 6:48:39 PM Imar Spaanjaars said:
Hi Michael,

Unfortunately, no I can't.

You can check if the file exists on the server, not on the client, so I suggest you use regular ASP.NET / HTML for that.

Alternatively, you could try the new Microsoft Ajax Framework....

On Tuesday, January 9, 2007 8:34:18 AM watt said:
Please can someone help me with how to create a Rotating image in dream without using timeline tools because I was able to do it with time line but It will not work with some browsers not even with the new version of Internet Explorer
I want a situation where group of images or pictures will be changing either randomly or sequential. thanx
On Monday, January 15, 2007 7:00:21 PM Roshan Raj said:
How can I change the filename of uploaded fiels dynamically so that they are unique in nature? Hope you can help out since I have been googling since morning.

Thanks in advance...
On Monday, January 15, 2007 7:04:07 PM Imar Spaanjaars said:
Hi Roshan,

You can use Guid.NewGuid().ToString() to generate a unique name and combine that with the extension of the original file.

Take a look here: for an implementation of this.


On Tuesday, January 16, 2007 9:57:49 AM Roshan Raj said:
Hi Imar,

Thank you very much for the response. It was useful.

I was wondering if theres a way to find the dimensions(width, height) of the uploaded images.

What I am trying to do is upload an image of size: 256px X 250px.

So I need to restrict the uploaded file to this size. No other size is permitted.

Once again thanks for the advance and your site is definitely a top class bookmark for me.

On Tuesday, January 16, 2007 6:41:43 PM Imar Spaanjaars said:
Hi Roshan,

If you have the file already uploaded to the server, take a look at this:

Checking the file at the *client* is a different story. I don't think you can check for that without lowered security settings and/or something like ActiveX.


On Tuesday, January 16, 2007 11:03:35 PM Roshan said:
Hi Imar,

Extremely greatful for your tip.

Sorry but correct me if I am wrong. The following is what I am trying:

1)Client has to upload a banner image using a web based form designed with an ASP.NET Fileupload control and button. This form is hosted on an external web server.

2)Client selects image to upload.

2)The Client hits the upload button after selecting the image residing on the client's hard drive.

3)The web server recieves the image file.

4)This file before storage has to be validated to ensure that the width is 250px and height is 250px respectively.

5)I know that we can check the Contenttype and ensure that the image size is in accordance to a certain value.

6)But I want to use ParameterLength to get the width and height of the image to validate against the set height and width.

Hope I am not bothering you a lot.

Thanks a lot Imar.


On Tuesday, January 16, 2007 11:07:13 PM Imar Spaanjaars said:
Hi Roshan,

Take a look here:

You can create a new Image based on the Stream from the uploaded file and then check its Width and Height. That way, you don't need to save it to disk first.

Hope this helps,

On Wednesday, January 17, 2007 10:28:57 AM Roshan Raj said:
Hi Imar,

You are the Guru! Awesome stuff mate. It all works now. The link you sent lead me to this link:

Life made easy.

Thanks for the help...

On Saturday, January 20, 2007 3:28:57 PM Imar Spaanjaars said:
For everyone looking for a detailed example of measuring the size of an uploaded image, check out this article:

Have fun,

On Thursday, March 8, 2007 10:53:37 PM KD said:
I want to do virus scan of the uploaded file before it is saved. How can I do it?

Also how can I convert uploaded image or word file to PDF file before it is saved to folder or database? Does .Net provide any class to convert to PDF or we have rely on 3rd party software?

On Friday, March 9, 2007 7:05:28 AM Imar Spaanjaars said:
Hi KD,

Yes, AFAIK, there is no built-in functionality for PDFs so you still need to use third party software.

Can't advice much on the virus scan. This largely depends on what your virus software lets you do and whether or not they offer a programmatic way to do it.


On Friday, March 9, 2007 3:45:17 PM KD said:
Do you know any good third party softwares. It should also generate thumbnails.
We are using Norton Antivirus. I am not sure whether it offer programatic way to scan file. One thing we can do is that upload file in specific folder under IIS machine. configure virus scan act on that folder as soon as it sees new file. After scanning, move that file to another folder or database. How is that?
On Sunday, March 11, 2007 3:02:24 PM Imar Spaanjaars said:
Hi KD,

I think you're better off posting this in a forum of one of the major anti-virus companies. I don't have much experience with this so I can't help.

On Tuesday, May 8, 2007 6:41:45 PM Arno said:
Great Post.

The upload object works really great.
One question tough.
I am creating a mailing in Ms Publisher. When the .html is saved it stores all the images in a seperate directory with the same name as the html file.
The upload object only uploads the file. How to upload the corresponding directory?

Cheers Arno
On Tuesday, May 8, 2007 6:52:01 PM Imar Spaanjaars said:
Hi Arno,

You'll need to upload those, one by one as well in a standard .NET application. There is, by default, no way to upload a folder or multiple files at once (other than using multiple upload controls).

However, there are commercial components available that let you do this. One of them can be found at but there are others as well.


On Monday, May 28, 2007 8:01:10 AM Govardhan Reddy said:

I wanna know while overwriting a file i'm calling a JavaScript function which cofirms me wether to overwrite it or not. but i found out dat then Script is compiled after the enter page is loaded, while the uploading of file is done while loading the page. I came to conclusion  dat javascript is not able return back to server side again if iam returning false.

Iam workin in Visual Studio 2005 envi.
So could u provide any solution for this. (not in AJAX).
On Monday, May 28, 2007 8:16:26 AM Imar Spaanjaars said:
Hi Govardhan,

Here's what I would do:

1. Check if the file exists.

2. Save the uploaded file like you normally would do if it doesn't.

3. Save the uploaded file with a temporary name if it already exists.

4. Round trip to the browser asking the user for permission to overwrite the file.

5. If they don't want to do it, either delete the temp file or give it a "copy of" kind of name.

6. If the user wants to overwrite, delete the old one and rename the temp file to the old name.

Hope this gives you some ideas.

On Friday, January 4, 2008 10:21:25 PM mann said:
hi imar,
First of all,I am so happy that i read this article,thats useful tip wich i was looking for.thanks to you..Also for your effort to help out the poor guys like us.......Also good luck for ur upcoming book.
     I read above that you cannot possibly reply all tech ques..but i tried at  p2p forum at and also in some sites.but yet no reply. i guess, all of em' have only problem..if u cud help,
1)y m i not getting all the backgrounds,pictures,banners etc from the browser after executing?, yet i can see it while in design grid.
2)I also tried uploading to sql server which worked do i download the files to the page then,both from sql and file system?
3)I am not that good at javascript,is it hopeless for me to became a web developer? i was trying to create interactive do i do it on .net?(but i dont want to use navigation menu controls) i checked many forums and other sites but no solution..

please help me..i know u hv less time , u donot have to answer but u cud provide me links..i would be pleased to click em'.
On Saturday, January 5, 2008 12:09:30 AM Imar Spaanjaars said:
Hi mann,

What's your user name on the Wrox forum? I searched but didn't find anything useful.

Anyway, regarding your questions:

1) No idea what you are talking about. It would really help if you provided more background information with these vague kind of questions. Again, the best place to (re)ask this question and provide more details is on the Wrox site.

2) Take a look here:

3) Being hopeless at something doesn't mean you can't learn it. I suck at Spanish, yet I try to master the language, and I know I will succeed some day.... ;-) Same applies here as to number 1: waaaaaaay too vague.

So, my suggestion is: write proper, specific questions, add lots of detail and post on the Wrox forum again. You can't expect a good answer if you don't ask good questions.


On Saturday, January 5, 2008 1:12:43 AM mann said:
my username is pepperoni00..
there i found you...actually u had responded with some solution to one of the fellow developer ..hence...

by the way thanks for response..
1st question i was talking about was...suppose,let's take this page for an example.. .you have heading "" in silver background; navigation buttons have orangy, those backgrounds are definitely some .jpg or gif files...likewise u cud hv some pictures or banners..
    Now,lets go to create a new website project in visual studio 2005.there i put some pictures,background etc,along with some buttons and other controls in the page..supposing, everthing is alrite,i execute it ..then a web browser  shows my page...everthing's correctly BUT,those pictures and background doesnot appear in the browser....however,if i change background by modifying appearance propery in properties works fine but i want to use my own background,own buttons etc..
..i tried changing ImageUrl,tried saving it in wwwroot folder,tried configuring IIS,tried everythig i cud i have to load em' seperately?...iv no idea...I am "new, fresh and eager" developer.i wanto learn more n more..I think i m going in rite direction until now..please,dont mind my long letter

anyway,i do appriciate the reply and thanks for the 2nd and 3rd answers.i guess ill check that link uv given...

On Saturday, January 5, 2008 9:37:35 AM Imar Spaanjaars said:
Hi Mann,

I checked your Wrox post and I think you're asking way too many questions in a single post, making it unattractive for someone to answer at least one of them if they know the answer.

Just create separate topics for separate questions, be clear and concise with your question and more importantly: describe what you do and post the code that doesn't work.


On Saturday, January 5, 2008 3:17:55 PM mann said:
Oh! thanks for suggns..
honestly, that was my first post in the forum..and i am pretty new..
thank you
with regards,
On Saturday, January 5, 2008 4:08:48 PM Imar Spaanjaars said:
Hi Mann,

Don't worry. That's why I gave you some tips for better questions.


On Thursday, February 21, 2008 7:18:09 PM Vic said:
Hi Imar,
I have done everything you have posted and more. All works great....  

I need to post the page and fill the file name into the upload control through the program or script and fire the upload automatically. I can't figure any way to do this. I have even tried doing a sendkeys with scripting host but the control refuses to take the value.

Our users pick their file from an available list, so I need to take that file name, put it into the control then fire the upload. Everything works fine except for loading the file name.
Is there any way to do this.

Thanks Vic
On Saturday, February 23, 2008 9:22:18 AM Imar Spaanjaars said:
Hi Vic,

Fortunately, you can't do what you want. Combined with a form that submits itself on page load you can steal whatever file from a user's computer simply by having them visit a page.

You need to rethink your strategy, as this won't work.

On Thursday, July 24, 2008 9:32:04 AM Balaji said:

  ur coding is not working in firefox. plz check it in firefox. and then give it to text all others.

  plz reply me.

On Thursday, July 24, 2008 10:46:27 AM Imar Spaanjaars said:
Hi Balaji,

Of course this code works in FireFox. It hardly has anything to do with FireFox as it's server side code.

So, please check your own coding to see where your error is.


On Saturday, December 6, 2008 10:36:22 AM RituRaj Pandey said:
hi, I am Software Engineer And i am living at Indor city at this time . i am very -2 thank full to this tutorials because i tried before 3 days for this problem .but this tutorials is provided to greate soluton for this i am thank full.
On Wednesday, December 10, 2008 10:31:00 PM Janice Long said:
Can you give an example of using the FileUpload control to start an FTP upload?
On Thursday, December 11, 2008 7:07:10 AM Imar Spaanjaars said:
Hi Janice,

You can't do this directly; you'll need other software (first or third party components) that FTP a file for you after it has been uploaded.


On Thursday, June 25, 2009 7:23:01 AM SAM said:
Hi Imar,
suppose that there r two operations in file uploading...... one to upload a file and then save its related information in the DB.---------

1. upload a file physically on the web server.
2. saving its information into DB.

now i want to use TRANSACTION for above two operation.

is it possible?
On Thursday, June 25, 2009 7:46:51 AM Imar Spaanjaars said:
Hi SAM ,

Nope, you can't because the File System is not transactional. However, you can save the file on disk, try to update the database and then when it fails delete the file again.

Also, you may want to take a look here if you want to know how to store files in the database:

Makes it slightly easier to do transactions.


On Tuesday, May 4, 2010 2:53:23 PM subhash said:
simple and helpful  code

On Wednesday, June 16, 2010 2:29:26 AM Deeepak said:
This is very useful site. I make a songs site and i want to make upload button for upload the song. Please send the script for it on my email id this is I realy thak full to you.
On Wednesday, June 16, 2010 6:18:41 AM Imar Spaanjaars said:
Hi Deeepak,

You're missing the point completely as this is exactly what this article is about.

On Saturday, September 4, 2010 9:15:53 AM Amruta said:
I have 2 different server in same domain. kindly guide me how to upload file in
On Monday, September 6, 2010 7:16:59 AM Imar Spaanjaars said:
Hi there,

Not exactly sure what you're asking, or how this is related to this article. Try posting it on a forum such as this one: and make sure you provide a lot more detail with your question.



Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.

For more information about the Talk Back feature, check out this news item.