C# CSV File Writer
Here is a C# CSV File Writer class you can use in all your projects. It provides basic functionality for writing data to CSV files and/or Datatables and/or DataRows.
Sample usage provided in the class level comments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
//CSV File Writer C# class file. //Class with basic functionality for writing data to CSV files. using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; namespace YourNameSpace { #region Sample Use /******************************************************************************** * Code adapted from * http://www.blackbeltcoder.com/Articles/files/reading-and-writing-csv-files-in-c * * Sample usage: string[][] rows; //rows/columns array : : //populate the rows and columns with data : using (CSVFileWriter writer = new CSVFileWriter("YourFile.csv")) { for (int x = 0; x < rows.Length; x++) { writer.WriteRow(rows[x]); } } * * *********************************************************************************/ #endregion Sample Use /// <summary> /// Class with basic functionality for writing data to CSV files. /// </summary> class CSVFileWriter : IDisposable { #region Private Members //Private members private StreamWriter _writer; private string _oneQuote = null; private string _twoQuotes = null; private string _quotedFormat = null; ///<summary> ///Special characters in CSV files. If a column contains any ///of these characters, the entire column is wrapped in double quotes. ///Some cultures use the semi-colon ";" instead of the comma "," as the CSV ///separator, so alter as appropriate or set through the Delimiter property. ///</summary> protected char[] SpecialCharacters = new char[] { ',', '"', '\r', '\n' }; //Indexes into SpecialCharacters for characters with a specific meaning private const int _delimiterIndex = 0; private const int _quoteIndex = 1; #endregion Private Members #region Public Properties ///<summary> ///Gets/sets the character used for column delimiters. Some cultures use ///the semi-colon ";" instead of the comma "," as the delimiter. ///</summary> public char Delimiter { get { return SpecialCharacters[_delimiterIndex]; } set { SpecialCharacters[_delimiterIndex] = value; } } ///<summary> ///Gets/sets the character used for column quotes. ///</summary> public char Quote { get { return SpecialCharacters[_quoteIndex]; } set { SpecialCharacters[_quoteIndex] = value; } } #endregion Public Properties #region Constructors ///<summary> ///Initializes a new instance of the CsvFileWriter class for the ///specified stream. ///</summary> ///<param name="stream">The stream to write to</param> public CSVFileWriter(Stream stream) { _writer = new StreamWriter(stream); } ///<summary> ///Initializes a new instance of the CsvFileWriter class for the ///specified file path. ///</summary> ///<param name="path">The name of the CSV file to write to</param> public CSVFileWriter(string path) { _writer = new StreamWriter(path); } #endregion Constructors #region Public Methods ///<summary> ///Writes a row of columns to the current CSV file. ///</summary> ///<param name="columns">The array of columns to write</param> public void WriteRow(string[] columns) { if (columns == null) throw new ArgumentNullException("The \"columns\" parameter cannot be null."); //Ensure we're using current quote character if (_oneQuote == null || _oneQuote[0] != Quote) { _oneQuote = String.Format("{0}", Quote); _twoQuotes = String.Format("{0}{0}", Quote); _quotedFormat = String.Format("{0}{{0}}{0}", Quote); } //Write each column for (int x = 0; x < columns.Length; x++) { //Add the delimiter if this isn't the first column if (x > 0) _writer.Write(Delimiter); //Write this column if (columns[x].IndexOfAny(SpecialCharacters) == -1) _writer.Write(columns[x]); else _writer.Write(_quotedFormat, columns[x].Replace(_oneQuote, _twoQuotes)); } _writer.WriteLine(); } ///<summary> ///Writes a row of columns to the current CSV file. ///</summary> ///<param name="columns">The list of columns to write</param> public void WriteRow(List<string> columns) { WriteRow(columns.ToArray<string>()); } ///<summary> ///Writes a datarow to the current CSV file. All objects ///in the datarow should be able to be converted to a string. ///Otherwise, this could fail. ///</summary> ///<param name="datarow">The datarow to write</param> public void WriteRow(DataRow datarow) { if (datarow == null) throw new ArgumentNullException("The \"datarow\" parameter cannot be null."); WriteRow(datarow.ItemArray.Cast<string>().ToArray()); } ///<summary> ///Writes a datatable to the current CSV file. ALl objects contained ///within the datatable should be able to be converted to a string. ///Otherwise, this could fail. ///</summary> ///<param name="datatable">The datatable to write</param> public void WriteDataTable(DataTable datatable) { if (datatable == null) throw new ArgumentNullException("The \"datatable\" parameter cannot be null."); for (int x=0; x < datatable.Rows.Count; x++) { WriteRow( datatable.Rows[x].ItemArray.Select(y => y.ToString()).ToArray() ); } } //Clean up everything public void Dispose() { _writer.Dispose(); if (SpecialCharacters != null) Array.Clear(SpecialCharacters, 0, SpecialCharacters.Length); SpecialCharacters = null; } #endregion Public Methods } //class } |