Home  >  Article  >  Backend Development  >  How to read a CSV file and store the values ​​into an array in C#?

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

WBOY
WBOYforward
2023-08-27 20:37:071360browse

如何在 C# 中读取 CSV 文件并将值存储到数组中?

A CSV file is a comma-delimited file used to store data in an organized manner. it Data is usually stored in tabular form. Most business organizations store their data in a CSV file.

In C#, the StreamReader class is used to process files. It opens, reads and helps Perform other functions to process different types of files. We can also perform different operations Use this class to operate on CSV files.

OpenRead() method is used to open CSV files, ReadLine() method is used to read its content.

OpenRead() method is used to open a CSV file, 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(&#39;,&#39;);
            foreach (var item in values){
               listA.Add(item);
            }
            foreach (var coloumn1 in listA){
               Console.WriteLine(coloumn1);
            }
         }
      } else {
         Console.WriteLine("File doesn&#39;t exist");
      }
      Console.ReadLine();
   }
}

Output

A
B
C

The above is the detailed content of How to read a CSV file and store the values ​​into an array in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete