public IEnumerable <T> Read(FileInfo fileInfo, CsvReaderOptions options) { fileInfo .ThrowExceptionIfNullOrDoesntExists() .ThrowExceptionIfExtensionIsDifferentFrom(Constants.FileExtensions.Csv); _options = options; var objects = new List <T>(); var headers = new List <string>(); using (var sr = new StreamReader(fileInfo.FullName, Encoding.GetEncoding(options.Encoding))) { var headersRead = !_options.HasHeader; string line; do { line = sr.ReadLine(); if (line != null && headersRead) { if (line.ToCharArray().Count(d => d == '"') % 2 == 1) { throw new FormatException($"Odd number of double quotes in line ${line}"); } var propertyValues = Regex.Split(line, _options.CsvDelimiter + "(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)") .Select(d => d.Replace("\"", string.Empty)).ToArray(); var obj = AssignValuesFromCsv(propertyValues, headers); objects.Add(obj); } if (!headersRead) { headersRead = true; if (line == null) { throw new FileLoadException($"{fileInfo.Name} is invalid. Probably it is empty..."); } headers = line.Split(_options.CsvDelimiter).ToList(); } } while (line != null); } return(objects); }
public IEnumerable <T> Read(FileInfo fileInfo) { CsvReaderOptions options = new CsvReaderOptions(); return(Read(fileInfo, options)); }