
Untitled
By: a guest on
Jun 20th, 2012 | syntax:
C# | size: 1.68 KB | hits: 417 | expires: Never
private DataTable readFromCSVFile(string filePath, string fileName)
{
StreamReader csvFile = File.OpenText(Path.Combine(filePath, fileName));
StringBuilder outputBuilder = new StringBuilder();
DataTable csvTable = new DataTable();
bool isFirstRow = true;
do
{
string line = csvFile.ReadLine();
ArrayList data = parseCsvString(line);
if (isFirstRow)
{
foreach (string field in data)
{
string fieldName = Utility.parseFieldName(field);
int fieldIndex = 1;
while(csvTable.Columns.Contains(fieldName))
fieldName += "_" + (++fieldIndex).ToString();
csvTable.Columns.Add(fieldName);
}
isFirstRow = !isFirstRow;
}
else
csvTable.LoadDataRow(data.ToArray(), true);
}
while (csvFile.Peek() != -1);
csvFile.Close();
return csvTable;
}
ArrayList parseCsvString(string line)
{
line += ",";
int lineLength = line.Length;
int startIndex = 0;
bool ignoreComma = false;
ArrayList parseResult = new ArrayList();
for (int loopIndex = 0; loopIndex < lineLength; loopIndex++)
{
char letter = line[loopIndex];
switch (letter)
{
case '\"':
ignoreComma = !ignoreComma;
break;
case ',':
if (!ignoreComma)
{
int datumLength = (loopIndex - startIndex);
if (datumLength > 0)
{
string datum = line.Substring(startIndex, datumLength);
parseResult.Add(Utility.fixQuotationMarks(datum));
}
else
parseResult.Add(string.Empty);
startIndex = loopIndex + 1;
}
break;
default:
break;
}
}
return parseResult;
}