Created
July 24, 2017 18:31
-
-
Save ZaneDubya/5c720ecaad8aaedcc562a0e9cd289c7c to your computer and use it in GitHub Desktop.
A generic reader for files containing comma separated values.
This file contains hidden or 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.IO; | |
namespace UMNCommonData.IO { | |
public class CsvReader { | |
public static CsvReader Open(string path, int fieldsRow, int firstDataRow, char separator) { | |
string[] lines = File.ReadAllLines(path); | |
string[] fields = lines[fieldsRow].Split(separator); | |
return new CsvReader(lines, fieldsRow, firstDataRow, separator); | |
} | |
public readonly string[] Fields; | |
readonly string[] _Lines; | |
readonly int _FirstDataRow; | |
readonly char _Separator; | |
const char QUOTE = '\"'; | |
public int Count => _Lines.Length - _FirstDataRow; | |
CsvReader(string[] lines, int fieldsRow, int firstDataRow, char seperator) { | |
_Lines = lines; | |
_Separator = seperator; | |
Fields = GetLine(fieldsRow); | |
_FirstDataRow = firstDataRow; | |
} | |
public string[] GetLine(int index) { | |
if (index < 0 || index >= Count) { | |
return null; | |
} | |
string line = _Lines[index + _FirstDataRow]; | |
string[] data = line.Split(_Separator); | |
while (Fields != null && data.Length != Fields.Length) { | |
for (int i = 0; i < data.Length - 1; i++) { | |
if (data[i].Length > 1 && data[i][0] == QUOTE && data[i][data[i].Length - 1] != QUOTE) { | |
data[i] = $"{data[i]}{_Separator}{data[i + 1]}"; | |
for (int j = i + 2; j < data.Length; j++) { | |
data[j - 1] = data[j]; | |
} | |
Array.Resize(ref data, data.Length - 1); | |
} | |
} | |
} | |
for (int i = 0; i < data.Length; i++) { | |
if (!string.IsNullOrEmpty(data[i]) && data[i][0] == QUOTE && data[i][data[i].Length - 1] == QUOTE) { | |
if (data[i].Length <= 2) { | |
data[i] = string.Empty; | |
} | |
else { | |
data[i] = data[i].Substring(1, data[i].Length - 2); | |
} | |
} | |
} | |
return data; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment