しばらく見回していると、ファイル内の行数を把握する方法についてかなりの数の議論が見つかりました。
たとえば、次の 3 つです。
c#テキスト ファイル内の行数をカウントする方法
テキスト ファイル内の行数を確認する 行数
をすばやくカウントするには?
それで、私は先に進み、私が見つけることができる最も効率的な(少なくともメモリに関しては?)と思われる方法を使用することになりました:
private static int countFileLines(string filePath)
{
using (StreamReader r = new StreamReader(filePath))
{
int i = 0;
while (r.ReadLine() != null)
{
i++;
}
return i;
}
}
しかし、ファイルの行自体が非常に長い場合、これには永遠に時間がかかります。これに対するより速い解決策は本当にありませんか?
StreamReader.Read()
orを使用しようとしましたがStreamReader.Peek()
、「もの」(chars? text?) があるとすぐにどちらかを次の行に移動させることはできません (または方法がわかりません)。
アイデアはありますか?
結論/結果(提供された回答に基づいていくつかのテストを実行した後):
以下の 5 つの方法を 2 つの異なるファイルでテストしたところ、一貫した結果が得られました。これは、プレーン オールドStreamReader.ReadLine()
が依然として最速の方法の 1 つであることを示しているようです。
ファイル #1:
サイズ: 3,631 KB
行数: 56,870
ファイル #1 の秒単位の結果:
0.02 --> ReadLine メソッド。
0.04 --> 読み取り方法。
0.29 --> ReadByte メソッド。
0.25 --> Readlines.Count メソッド。
0.04 --> ReadWithBufferSize メソッド。
ファイル #2:
サイズ: 14,499 KB
行数: 213,424
ファイル #1 の秒単位の結果:
0.08 --> ReadLine メソッド。
0.19 --> 読み取り方法。
1.15 --> ReadByte メソッド。
1.02 --> Readlines.Count メソッド。
0.08 --> ReadWithBufferSize メソッド。
以下は、私が受け取ったすべてのフィードバックに基づいてテストした 5 つの方法です。
private static int countWithReadLine(string filePath)
{
using (StreamReader r = new StreamReader(filePath))
{
int i = 0;
while (r.ReadLine() != null)
{
i++;
}
return i;
}
}
private static int countWithRead(string filePath)
{
using (StreamReader _reader = new StreamReader(filePath))
{
int c = 0, count = 0;
while ((c = _reader.Read()) != -1)
{
if (c == 10)
{
count++;
}
}
return count;
}
}
private static int countWithReadByte(string filePath)
{
using (Stream s = new FileStream(filePath, FileMode.Open))
{
int i = 0;
int b;
b = s.ReadByte();
while (b >= 0)
{
if (b == 10)
{
i++;
}
b = s.ReadByte();
}
return i;
}
}
private static int countWithReadLinesCount(string filePath)
{
return File.ReadLines(filePath).Count();
}
private static int countWithReadAndBufferSize(string filePath)
{
int bufferSize = 512;
using (Stream s = new FileStream(filePath, FileMode.Open))
{
int i = 0;
byte[] b = new byte[bufferSize];
int n = 0;
n = s.Read(b, 0, bufferSize);
while (n > 0)
{
i += countByteLines(b, n);
n = s.Read(b, 0, bufferSize);
}
return i;
}
}
private static int countByteLines(byte[] b, int n)
{
int i = 0;
for (int j = 0; j < n; j++)
{
if (b[j] == 10)
{
i++;
}
}
return i;
}