Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

File uploading for specific file types only in ASP.NET

Author: Rachel Nicole

In this article, I will explain how to upload file and how file extension can be checked for specific files to allow for uploading in ASP.NET.

 

  1. Open Visual Studio 2010
  2. File > New > Web Site
  3. Visual Basic or Visual C#  > ASP.NET Empty Web Site
  4. Right click on web site > Add New Item > Web Form
  5. Right click on website > New Folder. Rename the folder as “Files”.
  6. Write code below in Default.aspx page or Drag and drop following controls
    A FileUpload Control
    A Button Control
    A Label Control

    Select a File:
       
     <asp:FileUpload ID="FileUpload1" runat="server" />
       
     <br />
       
     <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
       
     <br />
       
     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
     
  7. Now comes the important part of this article. Write code below in button click event.
    Don’t forget to add the namespace given below as we are working with files.

    C#
     
    using System.IO;
     
    VB.NET
     
    Imports System.IO
     
    C#
     
    protected void Button1_Click(object sender, EventArgs e) {
            bool correctExtension = false;
     
            if (FileUpload1.HasFile) {
                string fileName = FileUpload1.PostedFile.FileName;
                string fileExtension = Path.GetExtension(fileName).ToLower();
                string[] extensionsAllowed = {".doc", ".docx", ".txt"};
     
                for (int i = 0; i < extensionsAllowed.Length; i++) {
                    if (fileExtension == extensionsAllowed[i]) {
                        correctExtension = true;
                    }
                }
     
                if (correctExtension) {
                    try {
                        string fileSavePath = Server.MapPath("~/Files/");
                        FileUpload1.PostedFile.SaveAs(fileSavePath + fileName);
                        Label1.Text = "File successfully uploaded";
                    }
                    catch (Exception ex) {
                        Label1.Text = "Unable to upload file";
                    }
                }
                else {
                    Label1.Text = "File extension " + fileExtension + " is not allowed";
                }
     
            }
        }
     
    VB.NET
     
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
     
            Dim correctExtension As Boolean = False
     
            If FileUpload1.HasFile Then
     
                Dim fileName As String = FileUpload1.PostedFile.FileName
                Dim fileExtension As String = Path.GetExtension(fileName).ToLower()
     
                Dim extensionsAllowed As String() = {".doc", ".docx", ".txt"}
     
                For i As Integer = 0 To extensionsAllowed.Length - 1
                    If fileExtension = extensionsAllowed(i) Then
                        correctExtension = True
                    End If
                Next
     
                If correctExtension Then
                    Try
                        Dim fileSavePath As String = Server.MapPath("~/Files/")
                        FileUpload1.PostedFile.SaveAs(fileSavePath + fileName)
                        Label1.Text = "File successfully uploaded"
                    Catch ex As Exception
                        Label1.Text = "Unable to upload file"
                    End Try
                Else
                    Label1.Text = "File extension " + fileExtension + " is not allowed"
                End If
     
            End If
     
     
        End Sub
     
  8. Here is the explanation of the code line by line.
     
    At the start of the “Button1_Click” method, I have declared a variable “correctExtension” and initializing it to “False”. It is used in the code to check the correct extension of the file which will be uploaded.
     
    In “If” statement expression, I have used the “HasFile” property of the “FileUpload” to check that “FileUpload” Control contains the file to upload.

    “FileName” property of “PostedFile” (Which is property of “FileUpload”) is used to get the name of the file and assigned this name to a “String” variable.

    Then I have another “String” variable to store the extension of the file. “Path” class has the “GetExtension()” method which takes the file name and returns the extension of that file. I have used “ToLower()” method to convert the extension into lower case.

    Next I have declared an “Array” of “Strings” (named extensionsAllowed) to store extensions which I want for files to be uploaded and initialized it with three file extensions. You can add more extensions of your interest in the same pattern.

    I have used “For” loop to loop through the “extensionsAllowed” array. It goes from index 0 to the index which is one less than the array length (“Length” property of the array is used to get the length).

    Inside the “for” loop, I have used an “If” statement to check that the extension of the file, that is selected for upload, is equal to one of my allowed extension to upload file. If it is so then I have set “correctExtension” variable to true.

    Then there is another “If” statement to check “correctExtension” variable. If it is “False” then I have displayed a message that this file extension is not allowed.

    On the other hand, if “correctExtension” variable is “True” then I have a “Try” block and a Catch” block.

    In “Try” block I have declared a variable “String” to save a path where I will save my files. “MapPath()” method of the “Server” object gets the string parameter of path and returns the complete physical path of the directory in the current website. Here “~/Files” means the folder “Files” exists at the root of the current website.

    “SaveAs” method of “PostedFile” property of the “FileUpload” gets the physical path (with file name) as string parameter and saves the file in that location.

    At the end, I am displaying message that the file is successfully uploaded.

    In “Catch” block I have just displayed an error message in case of any error. 
     
  9. Write click > Build web site and again right click > view in browser. 
  10. Try to upload files with different file extensions. You will see only files with extension “.doc”, “.docx” and “.txt” can be uploaded but files with other extensions like “.jpg”, “.mpeg”, “.mp3, and “.gif”” will not be uploaded unless you added these in extensions allowed.
So, File uploading for specific file types in ASP.NET is an easy task.

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< What is AJAX and how to use AJAX UpdatePanel Control in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net