Published on: 15 March, 2014

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

Posted by andy | 17131 views 1 likes 1 favourites 8 comments
Tumblr Digg Google Plus

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
Commented on: 02 Nov, 2016 10:31:37 AM
I tried the codes, didn't work.
andy
Commented on: 10 Nov, 2016 09:42:40 AM
What part of the code doesnt work? and what sort of error you get?
andy
Commented on: 18 Nov, 2016 10:31:09 AM
Hi Bob, I added the download project file. Try use this version.
Bob
Commented on: 15 Nov, 2016 04:48:57 AM
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.
wayne
Commented on: 16 Nov, 2016 12:59:45 AM
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
Commented on: 18 Nov, 2016 10:30:26 AM
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
Commented on: 19 Nov, 2016 02:24:15 AM
Many thanks Andy, I shall try this early next week and report back accordingly.
Rass Rass
Commented on: 31 Jan, 2017 03:28:42 PM
many thanks.. help me so much. Good posting and sharing Happy coding ^_^
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.
Share your article with us and add your own google adsense account to earn extra money. Plus, you can promote a link back to your site.
Related Articles
Published on: 13 February, 2017
One thing to remember when publishing your ASP.Net web applications, you may find out, some files could be not completely published due to the settings on the file properties. One example that I had are some font types file. In order to fix this problem you can navigate to the files that are missing and right click the properties.
Published on: 11 May, 2016
The slidingExpiration attribute is used in ASP.Net form authentication. This property is used to reset the expiration time for a valid authentication cookie if a request that has already being made has passed the timeout interval. Which means, if it is already expires, the current user will require to re-authentication again.
Related Tutorials