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 ToList(string filePath)
{
var result = new List();
string csvLine;
StreamReader file = new StreamReader(filePath);
while ((csvLine = file.ReadLine()) != null)
{
var obj = CSVFileReader.ToObject(csvLine);
result.Add(obj);
}
file.Close();
return result;
}
public static T ToObject(string csvString)
{
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;
}


}
}


Comments

Author: Gaurav Kumar Arora23 May 2016 Member Level: Gold   Points : 0

Good snippet, it'll be nice if you could add some description for code snippet.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: