Exemplo n.º 1
0
        public ParseResult <TDataRecord> ParseData(Stream fileStream, string separator)
        {
            if (fileStream == null || fileStream.Length <= 0)
            {
                throw new CsvParseException("File is empty");
            }
            var result = new ParseResult <TDataRecord>();

            try
            {
                var file = new StreamReader(fileStream);
                //
                //Stream stream = file;
                //DataTable csvTable = new DataTable();
                //using (CsvReader csvReader =
                //    new CsvReader(new StreamReader(stream), true))
                //{
                //    csvTable.Load(csvReader);
                //}

                var reader = new CsvReader(file);

                reader.Configuration.Delimiter = separator;
                reader.Configuration.IgnoreReadingExceptions = true;

                reader.Configuration.ReadingExceptionCallback = (ex, row) =>
                {
                    if (ex.GetType() == typeof(CsvTypeConverterException))
                    {
                        var error = ex.Data["CsvHelper"];

                        result.AddError("", string.Format("Could not read value {0}", error));
                    }
                    else
                    {
                        result.AddError("", "Could not read Csv file.");
                    }
                };

                while (reader.Read())
                {
                    var rowResult = ParseRow(reader);

                    if (!rowResult.IsValid)
                    {
                        result.AddErrors(rowResult.Errors);
                        return(result);
                    }
                    result.Records.Add(rowResult.Record);
                }
            }
            catch (CsvParseException ex)
            {
                result.AddError("", ex.Message);
            }
            catch (CsvMissingFieldException ex)
            {
                result.AddError("", ex.Message);
            }
            catch (Exception ex)
            {
                throw new CsvParseException("Coud not read csv file");
            }

            return(result);
        }