StreamWriter 中行的索引

Index of the line in StreamWriter

我正在使用 StreamWriter 写入文件,但我需要写入行的索引。

int i;
using (StreamWriter s = new StreamWriter("myfilename",true) {   
    i= s.Index(); //or something that works.
    s.WriteLine("text");    
}

我唯一的想法是读取整个文件并计算行数。有更好的解决方案吗?

一行的定义

line index 的定义,更具体地说,文件中的 line\n 字符表示。通常(在 Windows 上)这也可以在 return \r 字符之前,但不是必需的,通常不会出现在 Linux 或 Mac 上.

正确的解决方案

所以你要问的是当前位置的行索引基本上意味着你要问的是 \n 在你正在写入的文件中的当前位置之前存在的数量,这似乎是末尾(附加到文件),因此您可以将其视为文件中有多少行。

您可以读取流并对其进行计数,同时考虑您的机器 RAM,而不仅仅是将整个文件读入内存。所以这可以安全地用于非常大的文件。

// File to read/write
var filePath = @"C:\Users\luke\Desktop\test.txt";

// Write a file with 3 lines
File.WriteAllLines(filePath, 
    new[] {
        "line 1",
        "line 2",
        "line 3",
    });

// Get newline character
byte newLine = (byte)'\n';

// Create read buffer
var buffer = new char[1024];

// Keep track of amount of data read
var read = 0;

// Keep track of the number of lines
var numberOfLines = 0;

// Read the file
using (var streamReader = new StreamReader(filePath))
{
    do
    {
        // Read the next chunk
        read = streamReader.ReadBlock(buffer, 0, buffer.Length);

        // If no data read...
        if (read == 0)
            // We are done
            break;

        // We read some data, so go through each character... 
        for (var i = 0; i < read; i++)
            // If the character is \n
            if (buffer[i] == newLine)
                // We found a line
                numberOfLines++;
    }
    while (read > 0);
}

惰性解决方案

如果你的文件不是那么大(大取决于你预期的 machine/device RAM 和整个程序)并且你只想将整个文件读入内存(所以读入你的程序 RAM)你可以做一个班轮:

var numberOfLines = File.ReadAllLines(filePath).Length;