Example #1
0
        /// <summary>
        ///     convert csv stream data to dataTable
        /// </summary>
        /// <param name="stream">stream</param>
        public static DataTable ToDataTable(Stream stream)
        {
            if (stream is null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            var dt = new DataTable();

            if (stream.CanRead)
            {
                using var sr = new StreamReader(stream, Encoding.UTF8);
                string strLine;
                var    isFirst = true;
                while ((strLine = sr.ReadLine() !).IsNotNullOrEmpty())
                {
                    var rowData   = ParseLine(strLine);
                    var dtColumns = rowData.Count;
                    if (isFirst)
                    {
                        for (var i = 0; i < dtColumns; i++)
                        {
                            var columnName = rowData[i];
                            if (dt.Columns.Contains(columnName))
                            {
                                columnName = InternalHelper.GetEncodedColumnName(columnName);
                            }

                            dt.Columns.Add(columnName);
                        }

                        isFirst = false;
                    }
                    else
                    {
                        var dataRow = dt.NewRow();
                        for (var j = 0; j < dt.Columns.Count; j++)
                        {
                            dataRow[j] = rowData[j];
                        }

                        dt.Rows.Add(dataRow);
                    }
                }
            }

            return(dt);
        }