Created
October 2, 2013 11:50
-
-
Save dhlavaty/6792523 to your computer and use it in GitHub Desktop.
Simple CSV parser in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
namespace ConsoleApplication2 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string csvData = @"one,two,three | |
one,two,three"; | |
string[] lines = SplitCsvToLines(csvData); | |
for (var lineNum = 0; lineNum < lines.Length; lineNum++) | |
{ | |
var cells = SplitCsvLineToCells(lines[lineNum]); | |
// TODO: You can process cells[] in here | |
} | |
} | |
public static string[] SplitCsvToLines(string csv, char delimeter = '\n') | |
{ | |
csv = csv.Replace("\r\n", "\n").Replace("\n\r", "\n"); | |
List<string> lines = new List<string>(); | |
StringBuilder sb = new StringBuilder(); | |
bool isInsideACell = false; | |
foreach (char ch in csv) | |
{ | |
if (ch == delimeter) | |
{ | |
if (isInsideACell == false) | |
{ | |
// nasli sme koniec riadka, vsetko co je teraz v StringBuilder-y je riadok | |
lines.Add(sb.ToString()); | |
sb.Clear(); | |
} | |
else | |
{ | |
sb.Append(ch); | |
} | |
} | |
else | |
{ | |
sb.Append(ch); | |
if (ch == '"') | |
{ | |
isInsideACell = !isInsideACell; | |
} | |
} | |
} | |
if (sb.Length > 0) | |
{ | |
lines.Add(sb.ToString()); | |
} | |
return lines.ToArray(); | |
} | |
public static string[] SplitCsvLineToCells(string line, char delimeter = ',') | |
{ | |
List<string> list = new List<string>(); | |
do | |
{ | |
if (line.StartsWith("\"")) | |
{ | |
line = line.Substring(1); | |
int idx = line.IndexOf("\""); | |
while (line.IndexOf("\"", idx) == line.IndexOf("\"\"", idx)) | |
{ | |
idx = line.IndexOf("\"\"", idx) + 2; | |
} | |
idx = line.IndexOf("\"", idx); | |
list.Add(line.Substring(0, idx).Replace("\"\"", "\"")); | |
if (idx + 2 < line.Length) | |
{ | |
line = line.Substring(idx + 2); | |
} | |
else | |
{ | |
line = String.Empty; | |
} | |
} | |
else | |
{ | |
list.Add(line.Substring(0, Math.Max(line.IndexOf(delimeter), 0)).Replace("\"\"", "\"")); | |
line = line.Substring(line.IndexOf(delimeter) + 1); | |
} | |
} | |
while (line.IndexOf(delimeter) != -1); | |
if (!String.IsNullOrEmpty(line)) | |
{ | |
if (line.StartsWith("\"") && line.EndsWith("\"")) | |
{ | |
line = line.Substring(1, line.Length - 2); | |
} | |
list.Add(line.Replace("\"\"", "\"")); | |
} | |
return list.ToArray(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment