How to read a CSV file and store the values into an array in C#?

CsharpServer Side ProgrammingProgramming

A CSV file is a comma-separated file, that is used to store data in an organized way. It usually stores data in tabular form. Most of the business organizations store their data in CSV files.

In C#, StreamReader class is used to deal with the files. It opens, reads and helps in performing other functions to different types of files. We can also perform different operations on a CSV file while using this class.

OpenRead() method is used to open a CSV file and ReadLine() method is used to read its contents.

OpenRead() method is used to open a CSV file and ReadLine() method is used to read

Data.csv
A,B,C

Example

class Program{
   public static void Main(){
      string filePath =
      @"C:\Users\Koushik\Desktop\Questions\ConsoleApp\Data.csv";
      StreamReader reader = null;
      if (File.Exists(filePath)){
         reader = new StreamReader(File.OpenRead(filePath));
         List<string> listA = new List<string>();
         while (!reader.EndOfStream){
            var line = reader.ReadLine();
            var values = line.Split(',');
            foreach (var item in values){
               listA.Add(item);
            }
            foreach (var coloumn1 in listA){
               Console.WriteLine(coloumn1);
            }
         }
      } else {
         Console.WriteLine("File doesn't exist");
      }
      Console.ReadLine();
   }
}

Output

A
B
C
raja
Published on 25-Sep-2020 11:09:36
Advertisements