How to read a CSV file in C#

 

This class will allow you to read csv files.

It allows configurable delimiter and qualifier.

A qualifier is how to escape a field if it contains an instance of the delimiter.

There is a main method easy test.

 

 </code>namespace CSVReader
{
 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Text;

 /// <summary>
 /// Reads in a CSV file. Handles qualified fields.
 /// </summary>
 public class CSVReader
 {
 /// <summary>
 /// The stream reader used in the process
 /// </summary>
 private StreamReader streamReader;

 /// <summary>
 /// Initializes a new instance of the <see cref="CSVReader"/> class.
 /// </summary>
 /// <param name="sourceFile">
 /// The source CSV file being read.
 /// </param>
 /// <param name="delimeter">
 /// The delimeter used within the CSV file.
 /// </param>
 /// <param name="qualifier">
 /// The qualifier used within the CSV file.
 /// </param>
 /// <param name="removeQualifier">
 /// Dictates whether qualifying characters are to be removed.
 /// </param>
 public CSVReader(string sourceFile, char delimeter, char qualifier, RemoveQualifier removeQualifier)
 {
 this.SourceFile = sourceFile;
 this.Delimeter = delimeter;
 this.Qualifier = qualifier;
 this.DoRemoveQualifier = removeQualifier;
 }

 /// <summary>
 /// Finalizes an instance of the <see cref="CSVReader"/> class.
 /// </summary>
 ~CSVReader()
 {
 this.Close();
 }

 /// <summary>
 /// Determines whether to remove the quanlfying characters from each field
 /// </summary>
 public enum RemoveQualifier
 {
 /// <summary>
 /// Remove qualifying characters
 /// </summary>
 Yes,

 /// <summary>
 /// Do not remove qualifying characters
 /// </summary>
 No
 }

 /// <summary>
 /// Gets SourceFile; the CSV file being read
 /// </summary>
 public string SourceFile { get; private set; }

 /// <summary>
 /// Gets Delimeter used within the CSV file
 /// </summary>
 public char Delimeter { get; private set; }

 /// <summary>
 /// Gets Qualifier used within the CSV file.
 /// </summary>
 public char Qualifier { get; private set; }

 /// <summary>
 /// Gets DoRemoveQualifier. Whether to strip qualifying characters form the returned field
 /// </summary>
 public RemoveQualifier DoRemoveQualifier { get; private set; }

 public static void Main(string[] args)
 {

 var foo = new CSVReader("c:\\temp\\foo.csv", ',', '"', RemoveQualifier.Yes);

 List<String> lineData;

 while ((lineData = foo.ReadLine()).Count != 0)
 {

 var foo2 = lineData[0];
 }
 }

 /// <summary>
 /// Closes the stream reader
 /// </summary>
 public void Close()
 {
 if (this.streamReader == null)
 {
 return;
 }

 this.streamReader.Close();
 this.streamReader.Dispose();
 }

 /// <summary>
 /// Allows a peek to see if there are more lines.
 /// </summary>
 /// <returns>
 /// Returns true/false depending upon whether there are more lines to be read
 /// </returns>
 public bool IsMoreLines()
 {
 this.Open();

 if (this.streamReader != null)
 {
 return this.streamReader.Peek() != -1;
 }
 else
 {
 return false;
 }
 }

 /// <summary>
 /// Reads a line form the CSV file into a List of strings
 /// </summary>
 /// <returns>
 /// A generic List of string
 /// </returns>
 public List<string> ReadLine()
 {
 this.Open();

 var returnElements = new List<string>();

 try
 {
 var thisLine = this.streamReader.ReadLine();

 var lineElements = thisLine.Split(this.Delimeter);

 bool isQualifierOpen = false;

 string currentOpenQualifiedString = string.Empty;

 foreach (var lineElement in lineElements)
 {
 bool isQualified = false;

 int firstQualifiedIndex = lineElement.IndexOf(this.Qualifier);
 int lastQualifiedIndex = lineElement.LastIndexOf(this.Qualifier);

 if (firstQualifiedIndex != -1 && firstQualifiedIndex == lastQualifiedIndex)
 {
 isQualified = true;
 }

 // No open qualifier and not qualifier found.
 if (!isQualifierOpen && !isQualified)
 {
 if (firstQualifiedIndex != -1 && this.DoRemoveQualifier == RemoveQualifier.Yes)
 {
 // Self qualified
 returnElements.Add(this.RemoveQualifiers(lineElement));
 }
 else
 {
 returnElements.Add(lineElement);
 }

 continue;
 }

 if (isQualifierOpen && isQualified)
 {
 // Closing qualifier
 currentOpenQualifiedString = string.Format("{0},{1}", currentOpenQualifiedString, lineElement);

 if (this.DoRemoveQualifier == RemoveQualifier.Yes)
 {
 currentOpenQualifiedString = this.RemoveQualifiers(currentOpenQualifiedString);
 }

 returnElements.Add(currentOpenQualifiedString);
 currentOpenQualifiedString = string.Empty;
 isQualifierOpen = false;
 }
 else if (!isQualifierOpen)
 {
 // Open qualifier
 isQualifierOpen = true;
 currentOpenQualifiedString = lineElement;
 }
 else
 {
 // Continuing Qualifer eg "a,b,c,d". Need to add back in the comma.
 currentOpenQualifiedString = string.Format("{0},{1}", currentOpenQualifiedString, lineElement);
 }
 }
 }
 catch (Exception)
 {
 this.Close();
 }

 return returnElements;
 }

 /// <summary>
 /// Opens the stream reader
 /// </summary>
 private void Open()
 {
 if (this.streamReader == null)
 {
 this.streamReader = new StreamReader(this.SourceFile, Encoding.GetEncoding(1252));
 }
 }

 /// <summary>
 /// Removes the qualifying characters from a field string. This is the first and last occurance of the regiserted qualifying character
 /// </summary>
 /// <param name="qualifiedString">
 /// The a qualified string.
 /// </param>
 /// <returns>
 /// A string without starting and ending qualifiers
 /// </returns>
 private string RemoveQualifiers(string qualifiedString)
 {
 qualifiedString = qualifiedString.Remove(qualifiedString.IndexOf(this.Qualifier), 1);
 qualifiedString = qualifiedString.Remove(qualifiedString.LastIndexOf(this.Qualifier), 1);

 return qualifiedString;
 }
 }
}
<code> 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s