Technology Inside Out!

Index ¦ Archives ¦ Atom ¦ RSS

Asp.net Basics : Uploading a file in asp.net using validations (Part 4 of 5)

This is a part 4 of the 5 part tutorial.
If you are visiting this page for the first time then you must visit part 1 of the tutorial
on how to upload a file on server here

Contents of this 5 part tutorial
Part 1 : Basics of ASP.Net file uploading, uploading a file to a server.
Part 2 : ASP.Net file uploading using EmptyFile Validations.
Part 3 : ASP.Net file uploading using FileSize validation.
Part 4 : ASP.Net file uploading using FileExtension validator.
Part 5 : Complete ASP.Net file uploading using all the Validations one at a time.

FileUploadTut4-1


*File Upload in asp.net : v1.3 (File Extension Validation)*

This is the final part of the 5 part tutorial where we'll discuss about the FileExtension validations during file uploading. Some of the professional companies demand that the resume should be in .doc or .docx or .pdf extension only, so the main point arises what if the user uploads the file in some other extension (for example : in .txt file), there should be a validator for that to validate the extension of the file. Fortunately in Microsoft Visual Studio we can do that, there is a method GetExtension() which gets the extension of the file and has a return type of string.

GetExtension() method is saved in class Path which is the part of System.IO and returns a string. The complete syntax for using FileExtension validation is :-

string GetFileExtension = Path.GetExtension(FileUpload1.FileName);

where FileUpload1 is the fileupload control and FileName gets the current file which is being uploaded.

Using this method we can get the file extension and we can compare the values using if-else.

The complete C# code is

    private void GetFileExtension()
    {
        string GetFileExtension = Path.GetExtension(FileUpload1.FileName);
        if (GetFileExtension == ".pdf")
        {
            Image1.ImageUrl = "~//images//success.png";
            File_Extension.Text = "File Extension OK ! File will be uploaded";
            File_Extension.ForeColor = Color.GreenYellow;
            // Provide upload code (discussed in part 1 of this tutorial)
        }
        else
        {
            File_Extension.Text = "File Extension detected : '" +GetFileExtension+ "'. Required file extension : '.pdf' "+"File Not uploaded" ;
            File_Extension.ForeColor = Color.Red;
            Image1.ImageUrl = "~//images//not_success.png";
        }
    }

Output of the current code will be

FileUploadTut4-2

Thats the final part of the file upload system, in the next tutorial we'll add up all the part of this tutorial and present the final part of asp.net file upload tutorial.

© The Geeky Way. Built using Pelican. Theme by Giulio Fidente on github.

Disclaimer Privacy policy