1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- 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
- {
- /// <summary>
- /// Save the List data to CSV file
- /// </summary>
- /// <param name="list">data source</param>
- /// <param name="file">file</param>
- /// <returns>success flag</returns>
- public static string ToCsvFile<T>(this List<T> list, string file)
- {
- PropertyInfo[] props = GetPropertyInfoArray<T>();
- 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<T>()
- {
- 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();
- }
- }
|