Home » General, Programming / Coding

How to Check Uploaded File Extension – ASP .Net

27 July 2010 3,477 views 2 Comments

If you have fileUpload as your upload control
<input id="fileUpload" type="file" runat="server" />

This code sample check the file type if its an image. It can be altered for other file types as well. This example code is in C#.
HttpPostedFile myPostedFile=fileUpload.PostedFile;
if(myPostedFile!=null && myPostedFile.ContentLength>0)
{
FileInfo finfo = new FileInfo(myPostedFile.FileName);
string fileExtension = finfo.Extension.ToLower();
if (fileExtension != ".gif" && fileExtension != ".jpg" && fileExtension != ".jpeg" && fileExtension != ".png")
{
//show error message
return;
}
}

From Webcosmo Webmaster Forum http://www.webcosmoforums.com/asp/21239-how-check-uploaded-file-extension-asp-net.html

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 3.00 out of 5)
Loading ... Loading ...

2 Comments »

  • manu said:

    too good!!

  • Fewer said:

    when I changed the extension of a .pdf file to .jpg (but the file is not really a .jpg) this function does not return any error.
    Is there any way that does not look at the extension just writing in the full file name?

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.