Category: CRM Code Helpers

How to read a CSV file in a simplest way possible

Hello folks,

I am sure if you have been working with Microsoft Dynamics CRM or any other .net related application – you must have got this situation where you need to read data from a CSV file and do something with it for e.g. either to update this in CRM or write to other file.

here is the code that i used recently – i went through alot blogs and tutorials on how to do this but everything looked confusing to me. So I ended up doing this :

public string ReadCsv()
{
try
{

string csvPath = ConfigurationManager.AppSettings[“FilePath”]; // here i have used configuration manager as i am taking path from config file but you can simple pass the path in string “path” format.

//Read the contents of CSV file.
string csvData = File.ReadAllText(csvPath); // once you do this you will be able to read all the rows of the file. the format of the string would be like /r/n12341/r/n12344/r/rn2244……..

//Execute a loop over the rows.
foreach (string row in csvData.Split(‘\n’)) // removing the /n from the string you will get /r1234 in “row now
{

var id = row.Replace(“\r”, string.Empty); // finally removing “/r from the string.

//your logic goes here , either you can check each id , if this exist in CRM one by one using query by attribute or update this field in CRM etc.

}

 

i hope this helps!