IMG-LOGO

How to write csv text file and download the csv file as stream in ASP.Net C#?

andy - 15 Mar, 2014 34726 Views 12 Comment

In this tutorial, I will show you how to write sample data into a csv format and force the data to be downloaded as stream. I will use a StringBuilder object to append the content. For the example data, I will populate a simple customers data information that will contain customer id, name, email.

Firstly let's build the sample customer data. We will create a CustomerInfo object and a function that will return a list of CustomerInfo object list.

	//Customer Info object that will hold customer information.
public class CustomerInfo
{
    public int CustomerID { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

Now it is time to create a simple code routine that will write the data into csv text format and will force it as a downloaded stream.

	public partial class DownloadCSV : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(string.Format("{0},{1},{2}", "CustomerID", "Name", "Email") + Environment.NewLine);
            List<CustomerInfo> customerList = GetCustomers();
            foreach (CustomerInfo objCustomer in customerList)
            {
                sb.Append(string.Format("{0},{1},{2}", objCustomer.CustomerID.ToString(), objCustomer.Name, objCustomer.Email) + Environment.NewLine);
            }

            byte[] bytes = Encoding.ASCII.GetBytes(sb.ToString());
            if (bytes != null)
            {
                Response.Clear();
                Response.ContentType = "text/csv";
                Response.AddHeader("Content-Length", bytes.Length.ToString());
                Response.AddHeader("Content-disposition", "attachment; filename=\"sample.csv" + "\"");
                Response.BinaryWrite(bytes);
                Response.Flush();
                Response.End();
            }
        }

        //function that will return a list of customer information.
        public List<CustomerInfo> GetCustomers()
        {
            List<CustomerInfo> customerList = new List<CustomerInfo>();
            customerList.Add(new CustomerInfo { CustomerID = 1, Name = "Name 1", Email = "sample1@bytutorial.com" });
            customerList.Add(new CustomerInfo { CustomerID = 2, Name = "Name 2", Email = "sample2@bytutorial.com" });
            customerList.Add(new CustomerInfo { CustomerID = 3, Name = "Name 3", Email = "sample3@bytutorial.com" });
            return customerList;
        }

    }

One thing to remember, as CSV separate the field or each partial data with comma, if the partial data contains a comma, for ex: some data like address information like 32 george st, NSW Sydney. So you will need to wrap the content with double quote like "32 george st, NSW Sydney".

Download Files

Download

Comments

bob
02 Nov, 2016
I tried the codes, didn't work.
andy
10 Nov, 2016
What part of the code doesnt work? and what sort of error you get?
Bob
15 Nov, 2016
I didn't get any error, just couldn't launch the text file for download. Is it because I did it in a ContentPlaceHolder? codes from other sites didn't work either; I finally made it to bring up a .html page, and did the download there. Thank you for your responses.
andy
18 Nov, 2016
Hi Bob, I added the download project file. Try use this version.
wayne
16 Nov, 2016
Hi there, this code is writing the content of a csv file to the response body , but it doesn't fire up the Save As dialog box in IE 10. Can you assist?
andy
18 Nov, 2016
I just modify the code and add the download file project. Could you try run the project, it is built using VS 2015. if you are using lower version, just copy the code across.
Wayne
19 Nov, 2016
Many thanks Andy, I shall try this early next week and report back accordingly.
Rass Rass
31 Jan, 2017
many thanks.. help me so much. Good posting and sharing Happy coding ^_^
Danny
10 Jan, 2018
Thank you so much, this really helped a lot and helped me so much! Your post shows clear examples that is good explained.
Robert
24 May, 2018
1) I am trying to save 2 csv files to the same location. Is it possible to ask for the location just once? 2) Must the Response object be located in the current page's code-behind? I would like my button to simply call a method (in a static class located in a different .dll project) which would (after doing some things) use the Response object to prompt and save the 2 csv files. Thanks!
andy
25 May, 2018
Hi Robert, You can either add an extra input location in a form and pass it as a parameter string so you can use the location string as part of the csv location path. Regarding with separate project. Yes, this can be easily done, you can just create a new project linked to the main project and use the existing function.
Gtk
25 May, 2019
The code worked and was useful.
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to remove html tags from string in c#?

Sometimes you need to remove HTML tags from string to ensure there are no dangerous or malicious scripts especially when you want to store the string or data text into the database.