Monday, 2 April 2012

HOW TO CREATE AND DOWNLOAD A TEXT FILE USING C#

To create and download a text file with some text in it, 
In aspx page,
<asp:Button ID="Button1" runat="server" Text="Download" onclick="Button1_Click" />

In aspx.cs page,

protected void Button1_Click(object sender, EventArgs e)
{
    string text = "ASP.NET, C#, SQL SERVER, TIPS & TRICKS AND MORE..";  
    string attachment = String.Format("attachment; filename=Blog.txt");
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.AddHeader("content-disposition", attachment);
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.Write(text);
    HttpContext.Current.Response.End();
}


As you can see in the above code, the type of the file that has to be downloaded is specified in the ContentType. Similarly, we can download files with other extensions. For reference, take a look at the below formats .

".asf" = "video/x-ms-asf"
".avi" = "video/avi"
".doc" = "application/msword"
".zip" = "application/zip"
".xls" = "application/vnd.ms-excel"
".gif" = "image/gif"
".jpg"= "image/jpeg"
".wav" = "audio/wav"
".mp3" = "audio/mpeg3"
".mpg" "mpeg" = "video/mpeg"
".rtf" = "application/rtf"
".htm", "html" = "text/html"
".asp" = "text/asp"


1 comment:

  1. When I ran the app in VS2010, it correctly downloads the file to C:\Users\{UserName}\Downloads folder using the below code.

    string userDownloadFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads\\";
    But when I host the app in IIS, it goes to C:\Users\.NET 4.0 App Pool\Downloads\

    Yes the app pool is in .NET 4.0 App Pool.

    How I can get the logged in user's downloads folder by hosting the app in IIS?

    ReplyDelete