// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace E { public class CSVWriter { private static readonly Regex num = new Regex(@"\d+(\.\d+)?", RegexOptions.Compiled); private StreamWriter sw; private string fdelim; private string quot; private bool notquotnum; public CSVWriter(StreamWriter sw, string fdelim = ",", string quot = "\"", bool notquotnum = false) { this.sw = sw; this.fdelim = fdelim; this.quot = quot; this.notquotnum = notquotnum; } public void WriteLine(IEnumerable record) { bool first = true; foreach(string field in record) { if(first) first = false; else sw.Write(fdelim); bool q = notquotnum ? !num.IsMatch(field) : true; if(q) sw.Write(quot); sw.Write(field.Replace(quot, quot + quot)); if(q) sw.Write(quot); } sw.WriteLine(); } } public class Program { public static void Main(string[] args) { using(StreamWriter sw = new StreamWriter(@"C:\work\test.dat", false, Encoding.UTF8, 65536)) { CSVWriter csv = new CSVWriter(sw, ",", "\"", true); csv.WriteLine(new List { "ABC", "DEF", "123" }); csv.WriteLine(new List { "X,X", "Y\"Y", "456" }); } } } }