Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


Parse CSV File or Line
To Parse a CSV file it is best to use an established and tested library such as
Microsoft.VisualBasic.FileIO.TextFieldParser (this can be referenced from C#)

However if you really need to manually parse a line/file or want to modify the behavior, here is a method to Parse a CSV line. This can easily be adapted to parse an entire file. (The biggest gotcha is ensuring you handle lines even if column count varies throughout the file.)

For example, this handles the special case of ="03333", i.e. an Excel zip code, which TextFieldParser does not handle.

/// <summary>
/// Parses a CSV line as a one off without regard to overall column count
/// </summary>
/// <param name="line"></param>
/// <param name="escapeCharacter"></param>
/// <param name="delimiter"></param>
/// <returns></returns>
public static List<string> ParseCSVLine(string line, char escapeCharacter, char delimiter)
{
List<string> cols = new List<string>();
StringBuilder data = new StringBuilder();
bool escape = false;
foreach (char c in line)
{
if (char.IsWhiteSpace(c) && data.Length == 0)
{ } // ignore leading whitespace
else if (c == '=' && data.Length == 0 && !escape)
{ } // ignore leading equal signs from excel
else if (c == escapeCharacter && data.Length == 0 && !escape)
{
escape = true;
}
else if (c == escapeCharacter && !escape)
{
data.Append(c);
escape = true;
}
else if (c == escapeCharacter && escape)
{
escape = false;
}
else if (c == delimiter && !escape)
{
cols.Add(data.ToString());
data.Clear();
}
else
{
data.Append(c);
}
}
cols.Add(data.ToString());
return cols;
} // Parse

Created By: amos 10/24/2016 2:09:13 PM
Updated: 10/24/2016 2:22:37 PM