Wednesday, April 8, 2009

ASP.NET - Creating a CSV file and saving it to the client

This is fairly trivial using WinForms, but due to browser security you must use a different approach with ASP.NET. The following snippet gets the job done.

C# Code:

StringBuilder sb = new StringBuilder();
sb.Append("\"FirstName\", \"LastName\", \"State\",\"Comments\"\r\n");
sb.Append("\"John\", \"Doe\", \"CA\",\"embedded, comments, ink, this comment\"\r\n");
sb.Append("\"Jill\", \"Green\", \"NB\",\"\"\r\n");
sb.Append("\"Jack\", \"Smith\", \"ME\",\"\"\r\n\");
sb.Append("\"Rob\", \"Black\", \"NV\",\"\"\r\n");
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment; filename=test.csv");

Note: Always contain strings within double quotes. Otherwise embedded commas will be treated as delimiters.