/// <summary> /// Initializes a new instance of the <see cref="CsvRow"/> class. /// </summary> /// <param name="file"> /// The file. /// </param> public CsvRow(CsvFile file) { this.File = file; this.Values = new object[file.Columns.Count]; }
/// <summary> /// Loads from the specified stream reader. /// </summary> /// <param name="s">The stream reader.</param> /// <param name="cultureInfo">The culture info.</param> /// <returns> /// A <see cref="CsvFile" />. /// </returns> /// <exception cref="System.ArgumentNullException">s;The stream reader must be specified.</exception> /// <exception cref="System.InvalidOperationException">Invalid header.</exception> /// <exception cref="System.FormatException">Wrong number of columns on line + lineNumber</exception> public static CsvFile Load(StreamReader s, CultureInfo cultureInfo = null) { if (s == null) { throw new ArgumentNullException("s", "The stream reader must be specified."); } if (cultureInfo == null) { cultureInfo = CultureInfo.InvariantCulture; } var separator = cultureInfo.TextInfo.ListSeparator; var headerLine = s.ReadLine(); if (headerLine == null) { throw new InvalidOperationException("Invalid header."); } var headers = SplitLine(headerLine, separator[0]); int n = headers.Length; // Create a string collection for each column var items = new ValueList[n]; for (int i = 0; i < n; i++) { items[i] = new ValueList(); } // Read all rows int lineNumber = 1; while (!s.EndOfStream) { lineNumber++; var line = s.ReadLine(); if (line == null) { continue; } var fields = SplitLine(line, separator[0]); if (fields.Length != n) { throw new FormatException("Wrong number of columns on line " + lineNumber); } for (int i = 0; i < n; i++) { items[i].Add(fields[i]); } } var file = new CsvFile(); // Determine the type of each column from the data for (int i = 0; i < n; i++) { string name, unit; SplitHeader(headers[i], out name, out unit); file.Columns.Add(new CsvColumn(name, unit, items[i].GetSmallestCommonType(cultureInfo))); } // Parse the values (and box them) for (int j = 0; j < items[0].Count; j++) { var item = new CsvRow(file); for (int i = 0; i < file.Columns.Count; i++) { item.Values[i] = file.Columns[i].Convert(items[i][j], cultureInfo); } file.Rows.Add(item); } return(file); }