Reading csv file – LINQ

Let say you have csv file with two columns “Name” and “EmpID” and you want to use the values in your web based application.One option is to load the file into SQL server via some back end job and eliminate the use of file.But this will be only required (or suggested) if file is very huge.

I was having a web based application and my csv file holds some mapping information say Name and EmpId,Now i have silvelight page which calls web server methods via RIA and need to find EmpID from provided name.Below is the implementation tips with c#

//Read CSV file using LINQ

public class Employee
{
	public string Name {get;set;}
	public string EmpID {get;set;}
}

public class CSVReader{
	public static List ReadAllEmployees(){
		string fileName = HttpContext.Current.Server.MapPath("~/App_Data/Employee_Mapping.csv");
		List employees;
		employees = (from line in File.ReadAllLines(fileName, Encoding.Default)
                            let parts = line.Split(",".ToCharArray())
                            select new Employee() {Name=parts[0], EmpID=parts[1] }).ToList();
		return employees;
	}
}

Since the file will be used very frequently so you must hold the contents in the memory,you could add the list employee (Application_Start) into application state to achive this.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s