Introduction
This document describes how to create a. txt file and download it from your website.
Use Code
Although in the example, I first created a text file, but you do not have to do the same, because this file may already exist on your website. If so, you only need to use FileStream to read it.
First, read the text file to a byte array, and then use the Response object to write the file to the client.
Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);Response.ContentType = "application/octet-stream";Response.BinaryWrite(btFile);Response.End();
This code is the main code to complete this function. The first sentence adds a Header to the output, telling the browser that the file we sent to it is an attachment-type file. Then we set the output ContentType to "application/octet-stream", that is, to tell the browser to download this file, rather than display it in the browser.
Below is a list of MIME types.
". 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"
'All other files
= "Application/octet-stream"
The following is a complete sample code for downloading text files.
C#protectedvoid Button1_Click(object sender, EventArgs e){string sFileName = System.IO.Path.GetRandomFileName();string sGenName = "Friendly.txt";//YOu could omit these lines here as you may not want to save the textfile to the server//I have just left them here to demonstrate that you could create the text file using (System.IO.StreamWriter SW = new System.IO.StreamWriter(Server.MapPath("TextFiles/" + sFileName + ".txt"))){SW.WriteLine(txtText.Text);SW.Close();}System.IO.FileStream fs = null;fs = System.IO.File.Open(Server.MapPath("TextFiles/" + sFileName + ".txt"), System.IO.FileMode.Open);byte[] btFile = newbyte[fs.Length];fs.Read(btFile, 0, Convert.ToInt32(fs.Length));fs.Close();Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);Response.ContentType = "application/octet-stream";Response.BinaryWrite(btFile);Response.End();}
Summary
By using this method, you can download all file types in Windows. However, there may be some problems in the Macintosh system.