Code for .CSV to List object
In this Artice I will Explain sample code how to convert CSV file Contents to a List of Objects.
This is a generic CSV File reader which converts of the file contents to Generic type of List Objects.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace AHA.IS.LoggingPortal.Repository
{
public class CSVFileReader
{
public static List
{
var result = new List
string csvLine;
StreamReader file = new StreamReader(filePath);
while ((csvLine = file.ReadLine()) != null)
{
var obj = CSVFileReader.ToObject
result.Add(obj);
}
file.Close();
return result;
}
public static T ToObject
{
var values = csvString.Split(',');
Type typeOfT = typeof(T);
object objOfT = Activator.CreateInstance(typeOfT);
PropertyInfo[] propsinfo = typeOfT.GetProperties();
for (int i = 0; i < propsinfo.Length; i++)
{
var prop = propsinfo[i];
prop.SetValue(objOfT, Convert.ChangeType(values[i], prop.PropertyType));
}
return (T)objOfT;
}
}
}
Good snippet, it'll be nice if you could add some description for code snippet.