ReadToCSV.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using ConsoleApp1.model;
  2. using CsvHelper.Configuration;
  3. using CsvHelper;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace ConsoleApp1.read
  11. {
  12. internal class ReadToCSV
  13. {
  14. public List<T> ImportToCsv<T>(string path)
  15. {
  16. List<T> data = new List<T>();
  17. using (StreamReader reader = new StreamReader(path))
  18. {
  19. string line;
  20. while ((line = reader.ReadLine()) != null)
  21. {
  22. string[] values = line.Split(',');
  23. T item = Activator.CreateInstance<T>();
  24. var properties = typeof(T).GetProperties();
  25. for (int i = 0; i < properties.Length; i++)
  26. {
  27. properties[i].SetValue(item, Convert.ChangeType(values[i], properties[i].PropertyType), null);
  28. }
  29. data.Add(item);
  30. }
  31. }
  32. return data;
  33. }
  34. }
  35. }