Last post Feb 12, 2015 09:48 PM by Sherwin Zhao
Feb 12, 2015 01:51 AM|forestgump|LINK
I have some text data stored in SQL database. I want to provide the users a direct link for this data in order to download it as a text file. For an example,
www.example.com/1234.txt will download the text data which corresponds to the ID 1234 in the database. Is this possible ? if so any example code is highly appreciated.
Feb 12, 2015 09:48 PM|Sherwin Zhao|LINK
For your requirement, you need to load the file from database and then send the file to browser. The example code as below.
// Get a file from the database by ID
public static DataTable GetAFile(int id)
DataTable file = new DataTable();
using (SqlConnection connection = new SqlConnection())
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandTimeout = 0;
cmd.CommandText = "SELECT ID, Name, ContentType, Size, Data FROM Files "
+ "WHERE ID=@ID";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
cmd.Parameters["@ID"].Value = id;
adapter.SelectCommand = cmd;
protected void Page_Load(object sender, EventArgs e)
// Get the file id from the query string
int id = Convert.ToInt16(Request.QueryString["ID"]);
// Get the file from the database
DataTable file = FileUtilities.GetAFile(id);
DataRow row = file.Rows;
string name = (string)row["Name"];
string contentType = (string)row["ContentType"];
Byte data = (Byte)row["Data"];
// Send the file to the browser
Response.AddHeader("Content-Disposition", "attachment; filename=" + name);
More information please refer to the following link
Hope this can be helpful to you.