CSV Files in C#

4/3/2009

CSV (comma-seperated values) files are probably one of the easier items to deal with. For those of you who have never seen one of those files (I find that hard to believe actually), it's values seperated by commas... Well that and rows correspond to lines. But that's it. So most likely you aren't going to find this code extremely useful but I was tired of rewriting it every couple of weeks as every company under the sun seems to kick out info using it.

Delimited.cs

   1: /*
   2: Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
   3: 
   4: Permission is hereby granted, free of charge, to any person obtaining a copy
   5: of this software and associated documentation files (the "Software"), to deal
   6: in the Software without restriction, including without limitation the rights
   7: to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   8: copies of the Software, and to permit persons to whom the Software is
   9: furnished to do so, subject to the following conditions:
  10: 
  11: The above copyright notice and this permission notice shall be included in
  12: all copies or substantial portions of the Software.
  13: 
  14: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15: IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16: FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17: AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18: LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19: OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20: THE SOFTWARE.*/
  21:  
  22: #region Usings
  23: using System.Collections.Generic;
  24: using System.Text;
  25: using System.Text.RegularExpressions;
  26: #endregion
  27:  
  28: namespace Utilities.FileFormats.Delimited
  29: {
  30:     /// <summary>
  31:     /// Base classs for delimited files (CSV, etc.)
  32:     /// </summary>
  33:     public class Delimited
  34:     {
  35:         #region Constructor
  36:  
  37:         /// <summary>
  38:         /// Constructor
  39:         /// </summary>
  40:         public Delimited()
  41:         {
  42:         }
  43:  
  44:         /// <summary>
  45:         /// Constructor
  46:         /// </summary>
  47:         /// <param name="FileContent">File content</param>
  48:         public Delimited(string FileContent)
  49:         {
  50:             Regex TempSplitter = new Regex("[^\"\r\n$]*(\r\n|\n|$)|(([^\"\r\n$]*)(\"[^\"]*\")([^\"\r\n$]*))*(\r\n|\n|$)");
  51:             MatchCollection Matches = TempSplitter.Matches(FileContent);
  52:             foreach (Match Match in Matches)
  53:             {
  54:                 if (!string.IsNullOrEmpty(Match.Value))
  55:                 {
  56:                     Rows.Add(new Row(Match.Value, Delimiter));
  57:                 }
  58:             }
  59:         }
  60:  
  61:         #endregion
  62:  
  63:         #region Public Properties
  64:  
  65:         private List<Row> _Rows = new List<Row>();
  66:  
  67:         /// <summary>
  68:         /// The list of rows
  69:         /// </summary>
  70:         public List<Row> Rows
  71:         {
  72:             get { return _Rows; }
  73:             set { _Rows = value; }
  74:         }
  75:  
  76:         /// <summary>
  77:         /// The number of rows within the file
  78:         /// </summary>
  79:         public int NumberOfRows
  80:         {
  81:             get { return Rows.Count; }
  82:         }
  83:  
  84:         /// <summary>
  85:         /// Individual rows
  86:         /// </summary>
  87:         /// <param name="Position">The row that you want to get</param>
  88:         /// <returns>The row requested</returns>
  89:         public Row this[int Position]
  90:         {
  91:             get { return _Rows[Position]; }
  92:             set { _Rows[Position] = value; }
  93:         }
  94:  
  95:         /// <summary>
  96:         /// The delimiter used to seperate values (must be overridden)
  97:         /// </summary>
  98:         protected virtual string Delimiter { get { return ""; } }
  99:  
 100:         #endregion
 101:  
 102:         #region Public Overridden Function
 103:  
 104:         /// <summary>
 105:         /// To string function
 106:         /// </summary>
 107:         /// <returns>A string containing the file information</returns>
 108:         public override string ToString()
 109:         {
 110:             StringBuilder Builder=new StringBuilder();
 111:             foreach (Row CurrentRow in Rows)
 112:             {
 113:                 Builder.Append(CurrentRow.ToString());
 114:             }
 115:             return Builder.ToString();
 116:         }
 117:  
 118:         #endregion
 119:     }
 120: }

Row.cs

   1: /*
   2: Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
   3: 
   4: Permission is hereby granted, free of charge, to any person obtaining a copy
   5: of this software and associated documentation files (the "Software"), to deal
   6: in the Software without restriction, including without limitation the rights
   7: to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   8: copies of the Software, and to permit persons to whom the Software is
   9: furnished to do so, subject to the following conditions:
  10: 
  11: The above copyright notice and this permission notice shall be included in
  12: all copies or substantial portions of the Software.
  13: 
  14: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15: IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16: FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17: AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18: LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19: OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20: THE SOFTWARE.*/
  21:  
  22: #region Usings
  23: using System.Collections.Generic;
  24: using System.Text;
  25: using System.Text.RegularExpressions;
  26: #endregion
  27:  
  28: namespace Utilities.FileFormats.Delimited
  29: {
  30:     /// <summary>
  31:     /// Individual row within a delimited file
  32:     /// </summary>
  33:     public class Row
  34:     {
  35:         #region Constructors
  36:  
  37:         /// <summary>
  38:         /// Constructor
  39:         /// </summary>
  40:         public Row()
  41:         {
  42:         }
  43:  
  44:         /// <summary>
  45:         /// Constructor
  46:         /// </summary>
  47:         /// <param name="Content">Content of the row</param>
  48:         /// <param name="Delimiter">Delimiter to parse the individual cells</param>
  49:         public Row(string Content, string Delimiter)
  50:         {
  51:             Regex TempSplitter = new Regex(string.Format("(?<Value>\"(?:[^\"]|\"\")*\"|[^{0}\r\n]*?)(?<Delimiter>{0}|\r\n|\n|$)", Delimiter));
  52:             MatchCollection Matches = TempSplitter.Matches(Content);
  53:             bool Finished = false;
  54:             foreach (Match Match in Matches)
  55:             {
  56:                 if (!Finished)
  57:                 {
  58:                     Cells.Add(new Cell(Match.Groups["Value"].Value));
  59:                 }
  60:                 Finished = string.IsNullOrEmpty(Match.Groups["Delimiter"].Value) || Match.Groups["Delimiter"].Value == "\r\n" || Match.Groups["Delimiter"].Value == "\n";
  61:             }
  62:         }
  63:  
  64:         #endregion
  65:  
  66:         #region Public Properties
  67:  
  68:         private List<Cell> _Cells = new List<Cell>();
  69:  
  70:         /// <summary>
  71:         /// Cells within the row
  72:         /// </summary>
  73:         public List<Cell> Cells
  74:         {
  75:             get { return _Cells; }
  76:             set { _Cells = value; }
  77:         }
  78:  
  79:         /// <summary>
  80:         /// Returns a cell within the row
  81:         /// </summary>
  82:         /// <param name="Position">The position of the cell</param>
  83:         /// <returns>The specified cell</returns>
  84:         public Cell this[int Position]
  85:         {
  86:             get { return _Cells[Position]; }
  87:             set { _Cells[Position] = value; }
  88:         }
  89:  
  90:         /// <summary>
  91:         /// Number of cells within the row
  92:         /// </summary>
  93:         public int NumberOfCells
  94:         {
  95:             get { return Cells.Count; }
  96:         }
  97:  
  98:         #endregion
  99:  
 100:         #region Public Overridden Functions
 101:  
 102:         /// <summary>
 103:         /// To string function
 104:         /// </summary>
 105:         /// <returns>The content of the row in string form</returns>
 106:         public override string ToString()
 107:         {
 108:             StringBuilder Builder = new StringBuilder();
 109:             string Seperator = "";
 110:             foreach (Cell CurrentCell in Cells)
 111:             {
 112:                 Builder.Append(Seperator).Append(CurrentCell);
 113:                 Seperator = ",";
 114:             }
 115:             Builder.Append(System.Environment.NewLine);
 116:             return Builder.ToString();
 117:         }
 118:  
 119:         #endregion
 120:     }
 121: }

Cell.cs

   1: /*
   2: Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
   3: 
   4: Permission is hereby granted, free of charge, to any person obtaining a copy
   5: of this software and associated documentation files (the "Software"), to deal
   6: in the Software without restriction, including without limitation the rights
   7: to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   8: copies of the Software, and to permit persons to whom the Software is
   9: furnished to do so, subject to the following conditions:
  10: 
  11: The above copyright notice and this permission notice shall be included in
  12: all copies or substantial portions of the Software.
  13: 
  14: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15: IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16: FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17: AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18: LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19: OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20: THE SOFTWARE.*/
  21:  
  22: #region Usings
  23:  
  24: #endregion
  25:  
  26: namespace Utilities.FileFormats.Delimited
  27: {
  28:     /// <summary>
  29:     /// Cell within a delimited file
  30:     /// </summary>
  31:     public class Cell
  32:     {
  33:         #region Constructors
  34:  
  35:         /// <summary>
  36:         /// Constructor
  37:         /// </summary>
  38:         public Cell()
  39:         {
  40:         }
  41:  
  42:         /// <summary>
  43:         /// Constructor
  44:         /// </summary>
  45:         /// <param name="Content">Value within the cell</param>
  46:         public Cell(string Content)
  47:         {
  48:             Value = Content.Replace("\"", "");
  49:         }
  50:  
  51:         #endregion
  52:  
  53:         #region Public Properties
  54:  
  55:         private string _Value = string.Empty;
  56:  
  57:         /// <summary>
  58:         /// Value within the cell
  59:         /// </summary>
  60:         public string Value
  61:         {
  62:             get { return _Value; }
  63:             set { _Value = value; }
  64:         }
  65:  
  66:         #endregion
  67:  
  68:         #region Public Overridden Functions
  69:  
  70:         /// <summary>
  71:         /// To string function
  72:         /// </summary>
  73:         /// <returns>The value of the cell</returns>
  74:         public override string ToString()
  75:         {
  76:             return "\"" + Value + "\"";
  77:         }
  78:  
  79:         #endregion
  80:     }
  81: }

CSV.cs

   1: /*
   2: Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
   3: 
   4: Permission is hereby granted, free of charge, to any person obtaining a copy
   5: of this software and associated documentation files (the "Software"), to deal
   6: in the Software without restriction, including without limitation the rights
   7: to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   8: copies of the Software, and to permit persons to whom the Software is
   9: furnished to do so, subject to the following conditions:
  10: 
  11: The above copyright notice and this permission notice shall be included in
  12: all copies or substantial portions of the Software.
  13: 
  14: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15: IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16: FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17: AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18: LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19: OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20: THE SOFTWARE.*/
  21:  
  22: #region Usings
  23: using System.Collections.Generic;
  24: using System.Text;
  25: using System.Text.RegularExpressions;
  26: #endregion
  27:  
  28: namespace Utilities.FileFormats.CSV
  29: {
  30:     /// <summary>
  31:     /// CSV loader
  32:     /// </summary>
  33:     public class CSV:Delimited.Delimited
  34:     {
  35:         #region Constructor
  36:         
  37:         /// <summary>
  38:         /// Constructor
  39:         /// </summary>
  40:         public CSV() : base() { }
  41:  
  42:         /// <summary>
  43:         /// Constructor
  44:         /// </summary>
  45:         /// <param name="FileContent">File content</param>
  46:         public CSV(string FileContent) : base(FileContent) { }
  47:  
  48:         #endregion
  49:  
  50:         #region Properties
  51:  
  52:         protected override string Delimiter { get { return ","; } }
  53:  
  54:         #endregion
  55:     }
  56: }

You'll notice that the CSV class just inherits from the Delimited class and doesn't do much. The Delimited class actually does the row parsing and holds a list of Rows. The Rows then holds a list of Cells. The Cells hold the value. The cells are parsed based off of the Delimiter property set in the CSV class. The reason this is set up this way is so you can parse the values based off of other things also (pipes, tabs, etc.). Anyway, in order to use it all you do is read in the file, pass it into the CSV class and it will parse the file properly (creating the Rows and Cells as needed).  And if you want it back out, just call ToString... That's all there is to it, so give it a try, leave feedback, and happy coding.



Comments