File Handling File Handling

You can efficiently manage the file handling using File Handler in Here we will see how to create File Handler in When user selects files to download, file handler will process the file for downloading.

What should be the content type of file while downloading any type of file?

Answer is application/octet-stream.

Assuming client browser is adobe PDF enabled and you want the file of type PDF to be opened in browser, you need to tell browser about file content type as application/pdf.

For demo purpose, we have several files under “uploads” folder of my application. We have added new item generic handler in project which opens file for download and it’s contents are passed to Response output stream.

.aspx code.

<form id="form1" runat="server">
       &nbsp;<asp:RadioButtonList ID="RadioButtonList1" runat="server">
       <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Download" />
   </form> file selection code in

public partial class Limit_Download_Speed : System.Web.UI.Page
  protected void Page_Load(object sender, EventArgs e)
    if (!Page.IsPostBack)
      string path = Server.MapPath("uploads");
      string[] files = Directory.GetFiles(path);

      RadioButtonList1.DataSource = files;

  protected void Button1_Click(object sender, EventArgs e)
    string path = HttpUtility.UrlEncode( RadioButtonList1.SelectedValue);
    Response.Redirect("filehandler.ashx?filepath="+ path );
} with code for File selection.

Public Partial Class Limit_Download_Speed
	Inherits System.Web.UI.Page
	Protected Sub Page_Load(sender As Object, e As EventArgs)
		If Not Page.IsPostBack Then
			Dim path As String = Server.MapPath("uploads")
			Dim files As String() = Directory.GetFiles(path)

			RadioButtonList1.DataSource = files

		End If
	End Sub
	Protected Sub Button1_Click(sender As Object, e As EventArgs)
		Dim path As String = HttpUtility.UrlEncode(RadioButtonList1.SelectedValue)
		Response.Redirect("filehandler.ashx?filepath=" + path)

	End Sub
End Class

Description: Server.MapPath method maps the virtual path of folder to physical path on server.

GetFiles is Static method of Directory class found under System.IO namespace. It gives an array of files found at specified location

The collection of fully qualified filenames is assigned to Radio List box control of UrlEncode method is used to encode the request breaking characters found under file path. We are redirecting the request to FileHandler.ashx. In query string the filename is passed.

Let's see how FileHandler code looks. File Handler C# code example.

<%@ WebHandler Language="C#" Class="FileHandler" %>

using System;
using System.Web;

public class FileHandler : IHttpHandler {
    public void ProcessRequest (HttpContext context) 
        context.Response.ContentType = "application/octet-stream";
        context.Response.BufferOutput = false;        string selectedFilePath = context.Request.QueryString["filepath"];

        byte[] contents = System.IO.File.ReadAllBytes(selectedFilePath);         context.Response.Flush();
    public bool IsReusable {
        get {
            return false;


Description: Significance of IsReusable property of IHttpHandler interface.

When IsReusable returns true, it means that same instance of handler will be used for processing other requests to it. when it returns false, that means for every request to it will create new instance of handler.

We are taking the fully qualified name of file on server from query string. This is the file which is requested by user. ReadAllBytes is static method of File class. It returns bytes content of file from given location. Bytes content of file is then passed to Output stream of response and finally user gets the file.

At client side, user sees open save dialogue box. User can open,cancel or save the file on local system.

How to start instant file downloading without wait?.


User directly see open save dialoge as soon as he clicks on download button. File Handler with code example.

Imports System
Imports System.Web

Public Class FileHandler
	Implements IHttpHandler

	Public Sub ProcessRequest(context As HttpContext)

		context.Response.ContentType = "application/octet-stream"
		context.Response.BufferOutput = False

		Dim selectedFilePath As String = context.Request.QueryString("filepath")

		Dim contents As Byte() = System.IO.File.ReadAllBytes(selectedFilePath)




	End Sub

	Public ReadOnly Property IsReusable() As Boolean
			Return False
		End Get
	End Property

End Class


In image above, you can see File download dialogue box opened instantly at 0% bytes downloaded.

Now, you can limit file contents downloaded by user by counting the bytes. Store the count of bytes downloaded against the user and set limits per day.

Moving forward, you can store the IP of user and let the user wait for 20min or 60min after downloading specific amount of bytes. Something like famous Rapid Share download.

Tags: delete file file on Server and File UploadC# Delete All Files In DirectoryC# Get File Convert Image To Base64Could not load file or assembly SystemServiceModelDomainServicesHosting Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35 or one of its dependencies The system cannot find the file specifiedC# Read File Line By Lineasp net image uploadRead Text File in ( or File Interview Questions for 2 years or 3 years experiance


My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.

I'm Satalaj.