Download text data directly from SQL database RRS feed

  • Question

  • User721483249 posted


    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.

    Thank you... 

    Thursday, February 12, 2015 1:51 AM


  • User-2110585397 posted


    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.Add("@ID", SqlDbType.Int);
                    cmd.Parameters["@ID"].Value = id;
                    adapter.SelectCommand = cmd;
                return file;
            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[0];
                string name = (string)row["Name"];
                string contentType = (string)row["ContentType"];
                Byte[] data = (Byte[])row["Data"];
                // Send the file to the browser
                Response.AddHeader("Content-type", contentType);
                Response.AddHeader("Content-Disposition", "attachment; filename=" + name);

    More information please refer to the following link

    Hope this can be helpful to you.

    Sherwin Zhao
    Best Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 12, 2015 9:48 PM