Пример #1
0
        public CsvReadResult <T> GetRecords <T>(string fileContent) where T : ICsvRow, new()
        {
            if (string.IsNullOrWhiteSpace(fileContent))
            {
                throw new ArgumentNullException(nameof(fileContent));
            }

            var result = new CsvReadResult <T>();

            using (var reader = new StringReader(fileContent))
            {
                result = GetRecords <T>(reader);
            }

            return(result);
        }
Пример #2
0
        public CsvReadResult <T> GetRecords <T>(Stream inputStream) where T : ICsvRow, new()
        {
            if (inputStream == null)
            {
                throw new ArgumentNullException(nameof(inputStream));
            }

            var result = new CsvReadResult <T>();

            using (var reader = new StreamReader(inputStream))
            {
                result = GetRecords <T>(reader);
            }

            return(result);
        }
Пример #3
0
        private CsvReadResult <T> GetRecords <T>(TextReader reader) where T : ICsvRow, new()
        {
            var propertyMap = GetPropertyMappingConfig <T>();

            var result = new CsvReadResult <T>()
            {
                Errors = _errors,
            };

            int lineNumber = 0;

            using (reader)
            {
                string currentLine;

                while ((currentLine = reader.ReadLine()) != null)
                {
                    lineNumber++;

                    try
                    {
                        string[] currentRow = currentLine.Split(new[] { Config.Delimiter }, StringSplitOptions.None);

                        if (lineNumber == 1 && Config.HasHeaderRecord)
                        {
                            if (Config.ValidateHeader && !ValidateHeaderRow(propertyMap, currentRow))
                            {
                                _errors.Add(ValidateHeaderMessage(currentRow[0]));
                            }
                        }
                        else
                        {
                            T record = GetRecord <T>(propertyMap, lineNumber, currentRow);
                            result.Records.Add(record);
                        }
                    }
                    catch (Exception ex)
                    {
                        _errors.Add(CsvExceptionMessage(lineNumber, ex.Message));
                    }
                }
            }

            return(result);
        }