/// <summary> /// Save a list, or an array of, type-T objects to a file. /// </summary> /// <typeparam name="T">User's object type.</typeparam> /// <param name="list">An enumerable object providing CSV data source.</param> /// <param name="csvpath">Path to a csv file.</param> /// <param name="hc">See comments of enum HeaderCare.</param> /// <param name="encoding">Text file encoding of the csv.</param> /// <returns>CSV data lines written, not including the header line.</returns> public static int SaveCsvFile <T>(IEnumerable <T> list, string csvpath, HeaderCare hc = HeaderCare.None, Encoding encoding = null) where T : class, new() { int count = 0; if (encoding == null) { encoding = System.Text.Encoding.Default; } string correct_header_line = CsvLiner <T> .HeaderLine(); using (StreamWriter textwriter = new StreamWriter(csvpath, false, encoding)) { if ((hc & HeaderCare.Preserve) != 0) { textwriter.WriteLine(correct_header_line); } foreach (T tobj in list) { textwriter.WriteLine(CsvLiner <T> .Put(tobj)); count++; } } // using file return(count); }
/// <summary> /// Load a csv file and return an iterator of objects of user-given type(T). /// </summary> /// <typeparam name="T">User's object type.</typeparam> /// <param name="csvpath">Path to a csv file.</param> /// <param name="hc">See comments of enum HeaderCare.</param> /// <param name="encoding">Text file encoding of the csv.</param> /// <returns></returns> public static IEnumerable <T> LoadCsvFile <T>(string csvpath, HeaderCare hc = HeaderCare.None, Encoding encoding = null) where T : class, new() { if (encoding == null) { encoding = System.Text.Encoding.Default; } string correct_header_line = CsvLiner <T> .HeaderLine(); var csvlines = File.ReadLines(csvpath, encoding); using (var enumer = csvlines.GetEnumerator()) { if (!enumer.MoveNext()) { yield break; } string line0 = enumer.Current; bool is_line0_header = (line0 == correct_header_line) ? true : false; if ((hc & HeaderCare.Verify) != 0) { // Need verify CSV header if (!is_line0_header) { string s = $"CSV file does not have required headerline.\r\n" + $"CSV file:\r\n" + $" {csvpath}\r\n" + $"Required header line:\r\n" + $" {correct_header_line}\r\n"; throw new CsvLinerException(s); } } if ((hc & HeaderCare.Preserve) != 0) // user want to preserve first line { yield return(CsvLiner <T> .Get(line0)); } if (!is_line0_header) // first line is not a csv header { yield return(CsvLiner <T> .Get(line0)); } while (enumer.MoveNext()) { yield return(CsvLiner <T> .Get(enumer.Current)); } } // using enumerator }