Wednesday, 4 November 2015

File validation on size and extension



When you provide fileUpload button to let user upload some file, you surely require to validate the file extension and size of file.

Getting File Extension :

string fileExt = Path.GetExtension(fileUpload1.FileName);
//Here fileUpload1 is the fileUpload button id.

Now you can check this extension with the required extension.


Getting File Size :

  double fileSize = fileUpload1.FileBytes.Length;
// The fileSize will be in bytes.

Now just compare this value with the maximum file size allowed.



You can do the same in web.config File :


We use web.config to make settings global and more secure.


Web.config

 <appSettings>
    <add key="fileExtension" value=".txt"/>
    <add key="fileSize" value="1024"/>
 
  </appSettings>

// Means we are storing .txt at key fileExtension.
We could have saved more then one value by separating them by comma (,).


.cs file

string FileExtensionlist = ConfigurationManager.AppSettings["fileExtension"].ToString();
int FileSizeLimit = int.Parse(ConfigurationManager.AppSettings["fileSize"]);

Note:

 By default 4MB of file is allowed to be uploaded in asp.net.


If you want to increase the filesize validation then wrote following code in web.config:


maxRequestLength:

 Specifies the limit for the input stream buffering threshold in KB and allows you to control the allowed total size of the upload. Anything bigger than that will result in the default for the framework "Page not found" error.

ExecutionTimeout:

Specifies the maximum number of seconds for which a request is allowed to be executed before being automatically shut down by ASP.NET – the default time is 110 seconds. If the request takes longer to be executed, an exception will be thrown.


Code :

<system. web>

<httpRuntime maxRequestLength="102400" executionTimeout="3600" />

...

</system .web>

// /this will make the limit to 100MB. and execution time is 3600 sec.



No comments:

Post a Comment