如何在 C# 中讀取 CSV 檔案並將其中的值儲存為陣列?


CSV 檔案是一種以逗號分隔的檔案,用於以有序的方式儲存資料。它通常以表格形式儲存資料。大多數商業機構都將資料儲存在 CSV 檔案中。

在 C# 中,StreamReader 類用於處理檔案。它可以開啟、讀取和幫助對不同型別的檔案執行其他函式。我們還可以在使用此類時對 CSV 檔案執行不同的操作。

OpenRead() 方法用於開啟 CSV 檔案,ReadLine() 方法用於讀取其內容。

OpenRead() 方法用於開啟 CSV 檔案,ReadLine() 方法用於讀取內容。

Data.csv
A,B,C

示例

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

輸出

A
B
C

更新日期:2021 年 3 月 25 日

27K+ 瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告