Exemple #1
0
        /// <summary>
        /// Reads a CSV-File
        /// </summary>
        /// <param name="csvStream">CSV Stream Reader</param>
        /// <returns>CSV-Content</returns>
        public async Task <CsvReadResult> ReadCsvFile(Stream csvStream)
        {
            CsvReadResult readResult = new CsvReadResult();

            using (StreamReader streamReader = new StreamReader(csvStream))
            {
                string delimiter = await DetectDelimiter(csvStream, streamReader);

                CsvConfiguration configuration = new CsvConfiguration(CultureInfo.CurrentUICulture)
                {
                    Delimiter = delimiter
                };
                using (CsvReader csvReader = new CsvReader(streamReader, configuration))
                {
                    while (await csvReader.ReadAsync())
                    {
                        IDictionary <string, object> rowValues = csvReader.GetRecord <dynamic>() as IDictionary <string, object>;
                        if (rowValues == null)
                        {
                            continue;
                        }

                        AddMissingHeaders(readResult, rowValues);

                        readResult.Rows.Add(ReadRow(readResult.Columns, rowValues));
                    }
                }
            }

            return(readResult);
        }
Exemple #2
0
        /// <summary>
        /// Adds missing headers to a read result
        /// </summary>
        /// <param name="readResult">Read result</param>
        /// <param name="rowValues">Row values</param>
        private void AddMissingHeaders(CsvReadResult readResult, IDictionary <string, object> rowValues)
        {
            List <string> missingHeaders = rowValues.Keys.Where(k => !readResult.Columns.Contains(k)).ToList();

            if (!missingHeaders.Any())
            {
                return;
            }

            readResult.Columns.AddRange(missingHeaders);
            readResult.Rows.ForEach(r => missingHeaders.ForEach(h => r.Add(h, string.Empty)));
        }