Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If writing a CSV were a very complex task, I might rely on helpers like <code>CommaDelimitedStringCollection</code>. However, it isn't complicated, so there's no reason to introduce an extra helper class in here along with the associated perf hit.</p> <p>If I needed to build a string in memory for some reason, such as implementing a general <code>ToString()</code> method, I would use <code>StringBuilder</code> instead of straight concatenation. However, in this case you are writing to a stream of some kind, so you don't need this extra step either.</p> <p><code>TextWriter</code> is an abstract class, but you want the hierarchy of classes therein, specifically <code>StreamWriter</code>. This class has a number of constructor overloads; one takes a file name, if you want to write to a local file, and another takes a <code>Stream</code> object, if you want to write directly to a stream (for example <code>Response.OutputStream</code> in ASP.NET).</p> <p>I actually did a quick Google search and there don't appear to be any good examples of actually implementing a CSV download, if that's what you're trying to do, so here is one:</p> <pre><code>void ExportCsvAttachment(IEnumerable&lt;Customer&gt; customers) { Response.Clear(); Response.ContentType = "text/plain"; Response.AddHeader("Content-Disposition: attachment;filename=Customers.csv"); using (StreamWriter writer = new StreamWriter(Response.OutputStream)) { WriteCsv(writer, customers); } Response.End(); } void WriteCsv(TextWriter writer, IEnumerable&lt;Customer&gt; customers) { foreach (Customer cust in customers) { writer.Write(cust.ID); writer.Write(','); WriteCsvString(writer, cust.Name); writer.Write(','); WriteCsvString(writer, cust.PhoneNumber); } } void WriteCsvString(TextWriter writer, string s) { writer.Write('"'); writer.Write(s.Replace("\"", "\"\"")); writer.Write('"'); } </code></pre> <p>This uses the most common escaping mechanism for CSV - quotes around strings, another quote as an escape character.</p> <p>If you just want to export to a local file instead, get rid of all the <code>Response</code> lines in <code>ExportCsvAttachment</code> and use the <code>StreamWriter</code> constructor that takes a path.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload