How to validate file extension while uploading image or file through File Upload control in asp.net | Function to validate file extension before uploading image or file through FileUpload control in asp.net

Introduction: In previous articles i explained How to Validate and upload image files in asp.net and How to resize image in Asp.net and How to create thumbnail, small and large version of the uploaded image in Asp.net and How to bind gridview using DataReader,SqlCommand and Stored procedure in Asp.net and Difference between DataSet and DataTable in asp.net. Now i am going to explain with code example How to validate file/image extension before uploading the file to the server using FileUpload control in asp.net using both C# and VB.Net languages.

Description: Sometimes it is required to validate the file extension before uploading file i.e. you want that user can upload only the files that you want e.g. if you want the user can upload only .jpg, .jpeg, .png, .gif, .doc, .docx, .xls, .xlsx files then you have to write the code that can check the extension of the file the user is going to upload.

Implementation: Let's create an asp.net web application to understand.
  • Place a FileUpload control and a Button control on design page(.aspx) as:
  <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server"  Text="upload"
            onclick="btnUpload_Click" />

C#.Net Code to validate file extension while uploading image
  • In the code behind (.aspx.cs) file write the code:
Include namespaces:

using System.IO;

then write the code on upload button's click event as:
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (IsValidExtension())
        {
            //write code to upload file
            string filePath = (Server.MapPath("Uploads/") + Guid.NewGuid() + FileUpload1.FileName);
            FileUpload1.SaveAs(filePath);
        }
        else
        {
            return;
        }
    }

    protected bool IsValidExtension()
    {
        if (FileUpload1.HasFile)
        {
            string FileExt = Path.GetExtension(FileUpload1.FileName);

FileExt = FileExt.ToLower();
            if (FileExt != "gif" && FileExt != ".jpg" && FileExt != "jpeg" && FileExt != "png" && FileExt != ".doc" && FileExt != ".docx" && FileExt != ".xls" && FileExt != ".xlsx")
            {
                Response.Write("Please upload gif, jpeg, jpg, png, doc, docx, xls, xlsx file only");
                return false;
            }          
        }
        return true;
    }

VB.Net Code to validate file extension while uploading image
  • In the code behind (.aspx.vb) file write the code:
First Include namespace:

imports System.IO;
then write the code on upload button's click event

Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
                    If IsValidExtension() Then
                                         'write code to upload file
                                         Dim filePath As String = (Server.MapPath("Uploads/") + Guid.NewGuid() + FileUpload1.FileName)
                                         FileUpload1.SaveAs(filePath)
                    Else
                                         Return
                    End If
End Sub

Protected Function IsValidExtension() As Boolean
                    If FileUpload1.HasFile Then
                                         Dim FileExt As String = Path.GetExtension(FileUpload1.FileName)

FileExt = FileExt.ToLower()
                                         If FileExt <> "gif" AndAlso FileExt <> ".jpg" AndAlso FileExt <> "jpeg" AndAlso FileExt <> "png" AndAlso FileExt <> ".doc" AndAlso FileExt <> ".docx" AndAlso FileExt <> ".xls" AndAlso FileExt <> ".xlsx" Then
                                                             Response.Write("Please upload gif, jpeg, jpg, png, doc, docx, xls, xlsx file only")
                                                             Return False
                                         End If
                    End If
                    Return True
End Function

 Note: In this example Uploaded file will be saved in the Uploads folder. You can create a folder with different name and Replace the Uploads folder with the name of your Folder.

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..