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

WBOY
Release: 2023-08-27 20:37:07
forward
1439 people have browsed it

如何在 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
Copy after login

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();
   }
}
Copy after login

Output

A
B
C
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template