Озираясь некоторое время я нашел довольно много обсуждений того, как выяснить количество линий в файле.
For example these three:
c# how do I count lines in a textfile
Determine the number of lines within a text file
How to count lines fast?
Так, я шел вперед и закончил тем, что использовал то, что, кажется, является самым эффективным (по крайней мере, мудрый памятью?) метод, который я мог найти:
private static int countFileLines(string filePath)
{
using (StreamReader r = new StreamReader(filePath))
{
int i = 0;
while (r.ReadLine() != null)
{
i++;
}
return i;
}
}
Но это берет навсегда, когда сами линии от файла очень длинны. Есть ли действительно не более быстрое решение этого?
Я пытался использовать StreamReader. Читайте()
или StreamReader. Быстрый взгляд()
, но я не могу (или не знать, как к), заставляют любого из них идти дальше к следующей строке, как только есть 'материал' (случайные работы? текст?).
Какие-либо идеи, пожалуйста?
CONCLUSION/RESULTS (After running some tests based on the answers provided):
Я проверил эти 5 методов ниже на двух различных файлах, и я получил последовательные результаты, которые, кажется, указывают что простой StreamReader. ReadLine()
является все еще одним из самых быстрых путей... Честно говоря, я озадачен после всех комментариев и обсуждения в ответах.
File #1:
Size: 3,631 KB
Lines: 56,870
Results in seconds for File #1:
0.02 --> ReadLine method.
0.04 --> Read method.
0.29 --> ReadByte method.
0.25 --> Readlines.Count method.
0.04 --> ReadWithBufferSize method.
File #2:
Size: 14,499 KB
Lines: 213,424
Results in seconds for File #1:
0.08 --> ReadLine method.
0.19 --> Read method.
1.15 --> ReadByte method.
1.02 --> Readlines.Count method.
0.08 --> ReadWithBufferSize method.
Вот эти 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;
}