-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCsvParser.cs
More file actions
51 lines (48 loc) · 1.71 KB
/
CsvParser.cs
File metadata and controls
51 lines (48 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsvLibrary
{
public class CsvParser
{
public CsvParser()
{
}
public List<T> ReadFromCsv<T>(string FileName) where T : new()
{
List<T> Items = new List<T>();
List<string> columns = new List<string>();
using (var reader = new CsvFileReader(FileName))
{
while (reader.ReadRow(columns))
{
T Item = new T();
for (int i = 0; i < columns.ToList().Count(); i++)
{
Type t = Item.GetType();
var PropertyInfo = t.GetProperties()[i];
dynamic DynamicValue = columns.ToList()[i];
try
{
DynamicValue = Convert.ChangeType(DynamicValue, PropertyInfo.PropertyType);
}
catch
{
int column = i + 1;
throw new Exception("No se pudo cargar los datos del fichero " + FileName + ". El campo con valor '" + DynamicValue + "' de la columna " + column + " no pudo ser convertido al tipo " + PropertyInfo.PropertyType);
}
PropertyInfo.SetValue(Item, DynamicValue, null);
}
Items.Add(Item);
}
}
return Items;
}
public void WriteToCsv<T>(List<T> Items, string FileName)
{
throw new NotImplementedException();
}
}
}