Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement