// -------------------------------------------------------------------------------------------------------------------------- /// <summary> /// Add a line to the file, using reflection to read source data from the given type. /// </summary> public void AddLineFromData <T>(T data) { Type t = typeof(T); List <CSVColToPropertyMap> propList = CSVLine.GetPropList(t, ColumnMap); string[] vals = new string[ColumnMap.Count]; foreach (var p in propList) { int index = ColumnMap.GetIndex(p.ColName); if (index != -1) { object val = p.PropInfo.GetValue(data, null); string useVal = val?.ToString() ?? ""; // FixCSVData(val?.ToString() ?? ""); if (p.PropInfo.PropertyType == typeof(string)) { // Just quote all string fields... // Also make sure to escape any existing quotes. useVal = useVal.Replace("\"", "\"\""); useVal = "\"" + useVal + "\""; } vals[index] = useVal; } } Lines.Add(new CSVLine(ColumnMap, vals)); }
// -------------------------------------------------------------------------------------------------------------------------- public void AddLine(params string[] values) { CSVLine l = new CSVLine(this.ColumnMap); int index = 0; foreach (var v in values) { l[index] = v; ++index; } AddLine(l); }
// -------------------------------------------------------------------------------------------------------------------------- public CSVFile(string path, string separator = ",", bool includeHeader = true, bool trimWhitespace = true) { if (!File.Exists(path)) { throw new FileNotFoundException($"The file at path: {path} does not exist!"); } string[] splitWith = new[] { separator }; Separator = separator; using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (StreamReader r = new StreamReader(fs, Encoding.UTF8)) { // r.Read( string line = GetNextLine(r); string[] firstParts = line.Split(splitWith, StringSplitOptions.None); if (includeHeader) { int index = 0; foreach (var p in firstParts) { var cmap = new CSVColumnMapping() { Index = index, Name = GetColumnValue(firstParts, index, trimWhitespace) }; Columns.Add(cmap); ++index; } // it.MoveNext(); } else { // The first line is to be treated as data, so we will do that, but generate column names. for (int i = 0; i < firstParts.Length; i++) { var cmap = new CSVColumnMapping() { Index = i, Name = $"Column_{i + 1}", }; Columns.Add(cmap); } } // Now we can process all of the data...... Lines = new List <CSVLine>(); CSVColumnMap useCols = new CSVColumnMap(Columns); while ((line = GetNextLine(r)) != null) { CSVLine csvLine = new CSVLine(useCols, line, separator); Lines.Add(csvLine); } } return; }
// -------------------------------------------------------------------------------------------------------------------------- public void AddLine(CSVLine line) { Lines.Add(line); }