Thursday, July 10, 2025

How to create and download txt file programaticaly with asp.net c# and write content in it

   Response.Clear();

        Response.Write("This is an HttpHandler Test.");

        Response.Write("<p>Your Browser:</p>");


        Response.AddHeader("content-disposition", "attachment; filename=t.txt");

        Response.End(); 

How to download pdf file from server not on database only on server - Simplest way

//only two lines code is required that is uncommented

//Response.Clear(); // This is i am not using because response.clear is used for clearing http response (like text) but this is a file that is presently on server. Also when we create pdf of text file than we use clear function and we are getting pdf file from database (binary fromat) Response.buffer is default true so we don't need.

 Response.AddHeader("content-disposition", "attachment; filename=t.pdf"); 

 //Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf; 

        //"application/octet-stream"; 

        Response.WriteFile(Server.MapPath("~/App_Data/Annexure.pdf")); // File must be there on server otherwise it will give error


//Response.end is also we are not using because we are not creating pdf file , if we create pdf file or we are getting from database than we use Response.End and Response.Clear() functions.

Response.WriteFile or Response.TransmitFile use in asp.net c# - how to view pdf or text file in web browser

 It is used to show the content of any file in web browser.  This  is same as response.write but it will write the content of the file to web page. Mainly it is used to view the file content not to download the file.  Both Response.WriteFile or Response.TransmitFile  are same

example if text file than use code below

For PDF file

Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf;

Response.WriteFile(Server.MapPath("~/App_Data/Annexure.pdf"));


For txt file

Response.Clear(); 

     

        Response.ContentType = System.Net.Mime.MediaTypeNames.Text.Plain;  and use Text.html

        //"application/octet-stream"; 

        Response.WriteFile(Server.MapPath("~/App_Data/yash.txt"));

        Response.End(); 



or on page load, simply we can show the content of text file

Response.WriteFile("~/App_Data/" + fileName);