C#でテキストファイルのデータを逐次的に読み取る方法

C#では、StreamReaderクラスを使って、txtファイルのデータを1行ずつ読み込むことができます。以下にサンプルコードを示します:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "path_to_your_txt_file.txt";

        // 使用StreamReader打开文件
        using (StreamReader sr = new StreamReader(filePath))
        {
            string line;

            // 逐行读取文件数据
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}

上のコードでは、path_to_your_txt_file.txt を読み込む TXT ファイルのパスに置き換えます。すると、StreamReader クラスを使用してファイルを開き、ReadLine() メソッドを使用して、一行ずつ読み取ります。各行ぶんのデータを読み込んだ後は、後続の処理を行います。この例では、単に各行ぶんのデータをコンソールに print しています。

bannerAds