Files
LeafWeb/Core/Parsers/CsvParserBase.cs
T
2015-12-04 10:15:51 -05:00

49 lines
1.1 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using CsvHelper;
using CsvHelper.Configuration;
namespace LeafWeb.Core.Parsers
{
public class CsvParserBase : IDisposable
{
protected readonly FileSystemInfo CsvFile;
private readonly StreamReader _reader;
protected readonly CsvReader CsvReader;
protected CsvParserBase(FileSystemInfo csvFile)
{
CsvFile = csvFile;
if (!csvFile.Exists)
throw new FileNotFoundException($"Cannot find file '{csvFile.Name}'");
_reader = File.OpenText(csvFile.FullName);
var csvConfiguration = new CsvConfiguration { HasHeaderRecord = false, IgnoreBlankLines = false};
CsvReader = new CsvReader(_reader, csvConfiguration);
}
protected string[] GetNextCsvRowValues()
{
// get values from row
if (!CsvReader.Read())
return null;
// put all the values from this row into an array
var values = new List<string>();
var index = 0;
string value;
while (CsvReader.TryGetField(index, out value))
{
values.Add(value);
index++;
}
return values.ToArray();
}
public void Dispose()
{
_reader.Dispose();
}
}
}