Basics : Uploading a file in using validations (Part 2 of 5)

This is a part 2 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


File Upload in : v1.1 (Empty File Validation)

The first validation used is the empty file validation, what if the user doesn’t upload a file and simply pres the upload button, here is the output if the user presses only the upload button. Then an exception error will be generated on the server side.

Now since in tutorial 1 we discussed on how to upload file to server without any validations now we are using our first validation Empty File Validation it checks whether the user has selected the file or not in file control panel or if the user has directly clicked the upload button without selecting the file. If the user has directly clicked the upload button then an exception System.IO.DirectoryNotFoundException will be generated.

Here is the image below showing the details of the exception.

DirectoryNotFoundException2 ways of handling this exception

1. Using try-catch mechanism

Now since DirectoryNotFound Expression is thrown by the server then it can be caught by the try-catch mechanism.
The C# code for method 1 (try-catch) is :-

The output of the above code will be following images

Image 1 : The interface for the upload mechanism
Image 2 : Clicking the upload button when no file is selected.
Image 3 : Clicking the upload button when a file is selected and uploaded.




2. Using Boolean property “HasFile”

Another way of handling this exception is by using the Boolean property “HasFile” which will return the value as true or false. If the value returned is false then you can return the error message else it can continue with the uploading of file.
The C# code for method 2 (Boolean method) is :-


Thats all for the empty file validations property. In the next part of our tutorial we’ll discuss about the SizeValidation( Limiting the size of upload on the server).

Leave a Reply

Your email address will not be published. Required fields are marked *