C# テキストファイル内のデータの行数をカウントする

  • 作成日 2021.06.20
  • 更新日 2022.03.01
  • C#
C# テキストファイル内のデータの行数をカウントする

C#で、ReadAllLinesを使用して、読み込んだファイルのデータの行数をカウントするサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Microsoft Visual Studio Community 2019 Version 16.7.1

行数カウント

Lengthを使用すると、行数をカウントすることが可能です。

データ.Length

以下は、「sample.txt」に記述されている2行の「Hello World!」という文字列を取得して行数をカウントするサンプルコードとなります。

sample.txt

ソースコード

using System;
using System.IO;
using System.Text;

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {

            string[] lines = File.ReadAllLines("sample.txt");
            Console.WriteLine(lines.Length);
            // 2
            Console.ReadKey();

        }
    }
}