using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; public static class ListExtension { /// /// Save the List data to CSV file /// /// data source /// file /// success flag public static string ToCsvFile(this List list, string file) { PropertyInfo[] props = GetPropertyInfoArray(); using (var sw = new StreamWriter(file)) { StringBuilder strColumn = new StringBuilder(); for (int i = 0; i < props.Length; i++) { strColumn.Append(props[i].Name); strColumn.Append(","); } strColumn.Remove(strColumn.Length - 1, 1); sw.WriteLine(strColumn); //write the column name for (int i = 0; i < list.Count; i++) { StringBuilder strValue = new StringBuilder(); int idx = 0; foreach (var prop in props) { var val = prop.GetValue(list[i]); strValue.Append(val); if (idx < props.Length-1) strValue.Append(","); idx++; } sw.WriteLine(strValue); //write the row value } } FileInfo f = new FileInfo(file); return f.FullName; } private static PropertyInfo[] GetPropertyInfoArray() { PropertyInfo[] props = null; Type type = typeof(T); object obj = Activator.CreateInstance(type); props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); return props.Where(p => p.CanRead && !p.GetMethod.IsVirtual && !p.GetMethod.IsAbstract).ToArray(); } }