Downloading Different Types of File from Server using ASP.NET C#

In this article we are going to see How to download different types of file from the server. Follow the steps and comments above code for clear understanding.

File Types like: PDF, TXT, XLS etc

Design View:

a1img.png

Used Namespace:

using System;
using System.Web;

Step 1 : This is used to get Project Location to download File inside the Current Project.

/// <summary>
/// This is used to get the current Project Location.
/// </summary>
public static string ServerMapPath(string path)
{
   return HttpContext.Current.Server.MapPath(path);
}

Step 2: Next Step, we have to get the current response.

/// <summary>
/// This is used to get Current Response.
/// </summary>
public static HttpResponse GetHttpResponse()
{
   return HttpContext.Current.Response;
}

Step 3: This method Helps to download any type of File within the server by passing filename in parameter.
 

/// <summary>

/// This is used to download file from server.

/// </summary>

/// <param name="fileName"></param>

public static void DownLoadFileFromServer(string fileName)
{

     //This is used to get Project Location.

     string filePath = ServerMapPath(fileName);
     //This is used to get the current response.

     HttpResponse res = GetHttpResponse();

     res.Clear();
     res.AppendHeader("content-disposition", "attachment; filename=" + filePath);

     res.ContentType = "application/octet-stream";

     res.WriteFile(filePath);

     res.Flush();

     res.End();

}

Step 4: Creating Event for Button to download File from server by providing filename in the textbox.

protected
void Button1_Click(object sender, EventArgs e)
{
   
//string fileName = "DownloadTextFile.txt";
   
string fileName = FileNameTxt.Text;
   
//This method helps to download File from Server.
    DownLoadFileFromServer(fileName);
}

Thus I have explained how to Download File form server by specifying filename.

Thanks for reading this article. Have a nice day.