Tuesday, 21 August 2018

C#: Read from CSV

I'm writing this post thinking how easy it is to read and write to a file for a developer, however if you happen to write a piece of code to read from CSV i bet you take little longer. This is what happened to me. So i thought it's a good move to add this to my blog so i can refer this method anytime. 

If you think this helps you, make use of it whenever you want it.

Reference:

using System.IO;


Method to read from CSV: 

 public string[,] readCSV(string filePath)
        {
            try
            {
                string fileData = System.IO.File.ReadAllText(filePath);
                // Split into lines.
                fileData = fileData.Replace('\n', '\r');
                string[] lines = fileData.Split(new Char[] { '\r' }, StringSplitOptions.RemoveEmptyEntries);
                // See how many rows and columns there are.
                int totalRows = lines.Length;
                int totalCols = lines[0].Split(',').Length;
                // Allocate the data array.
                string[,] resultVals = new string[totalRows, totalCols];
                //populate the array with data
                for (int row = 0; row < totalRows; row++)
                {
                    string[] line_r = lines[row].Split(',');
                    for (int col = 0; col < totalCols; col++)
                    {
                        resultVals[row, col] = line_r[col];
                    }
                }
                return resultVals;
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("There was an error reported! {0} \n\n", ex.Message, ex.StackTrace);
                return null;
            }
        }


Method that use the string array:

 private void StartSearching(string[,] strArray)
        {
            try
            {
                for (int i = 1; i < strArray.GetLength(0); i++)
                {
 
                        Narnum = strArray[i,0].ToString().TrimEnd().ToLower();
                        EmpName = strArray[i,1].ToString().Trim();
                        PreferredName = strArray[i,2].ToString().TrimEnd();
                        Firstname = strArray[i,3].ToString().TrimEnd();
                        Surname = strArray[i,4].ToString().TrimEnd();
                        Position = strArray[i,5].ToString().TrimEnd();
                        Department = strArray[i,6].ToString().TrimEnd();
                        Manager = strArray[i,7].ToString().TrimEnd();
                        Division = strArray[i,8].ToString().TrimEnd();

     Validate(Narnum, EmpName, Position, PreferredName, Surname, Firstname, Manager, Division);

                }
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("There was an error reported! {0} \n\n", ex.Message, ex.StackTrace);
            }

        }





No comments:

Post a Comment