【问题标题】:Index of the line in StreamWriterStreamWriter 中行的索引
【发布时间】:2018-09-17 14:09:44
【问题描述】:

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

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

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

【问题讨论】:

  • @rene:副本似乎是关于流式阅读器,而不是流式写入器,而且关于该问题的答案将如何应用在这里并不明显......
  • @Chris 嗯,这是真的,我找不到另一个副本。重新打开和编辑
  • 为什么不能使用i++; 而不是i = s.Index();?或者你是否也在你的文本中写了\r\n?
  • @rene:请注意作者正在附加,因此大概操作人员需要知道已经存在多少条线,然后才能进行自己的跟踪。
  • 那是一种死胡同。他们仍然需要 StreamReader,或者至少读取文件中已有的内容。

标签: c# file streamwriter


【解决方案1】:

线的定义

line index 的定义,更具体地说,line 在文件中的定义由 \n 字符表示。通常(在 Windows 上也是如此)这也可以在回车符之前加上 \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);
}

懒惰的解决方案

如果您的文件不是那么大(大取决于您预期的机器/设备 RAM 和整个程序)并且您只想将整个文件读入内存(因此读入您的程序 RAM),您可以做一个班轮:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 2012-02-12
    • 2012-01-19
    • 1970-01-01
    • 2021-11-05
    • 2015-04-15
    • 2016-08-11
    相关资源
    最近更新 更多