ASP.net File Handling

ASP.net File Handling

You can efficiently manage the file handling using File Handler in Asp.net. Here we will see how to create File Handler in Asp.net. When user selects files to download, asp.net 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 asp.net 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">
   <div>
       &nbsp;<asp:RadioButtonList ID="RadioButtonList1" runat="server">
       </asp:RadioButtonList></div>
       <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Download" />
   </form>

Asp.net file selection code in C#.net.

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;
      RadioButtonList1.DataBind();


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

Asp.net with VB.net 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


			RadioButtonList1.DataBind()
		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 Asp.net. 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.

Asp.net 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();
        context.Response.BinaryWrite(contents);
       
        context.Response.End();  
        
    }
 
    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?.

context.Response.Flush();

User directly see open save dialoge as soon as he clicks on download button.

Asp.net File Handler with VB.net 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)

		context.Response.Flush()

		context.Response.BinaryWrite(contents)

		context.Response.[End]()

	End Sub

	Public ReadOnly Property IsReusable() As Boolean
		Get
			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:

Asp.net delete file file on Server C#.net and VB.net codeAsp.net File UploadC# Delete All Files In DirectoryC# Get File SizeAsp.net Convert Image To Base64Could not load file or assembly SystemServiceModelDomainServicesHosting Version=4.0.0.0, 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 (C#.net or VB.net)C# File ExistsAsp.net Interview Questions for 2 years or 3 years experiance

Author

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 ASP.net 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.