C# StreamWriter中的线索引
我正在使用StreamWriter写入文件,但我需要写入的行的索引C# StreamWriter中的线索引,c#,file,streamwriter,C#,File,Streamwriter,我正在使用StreamWriter写入文件,但我需要写入的行的索引 int i; using (StreamWriter s = new StreamWriter("myfilename",true) { i= s.Index(); //or something that works. s.WriteLine("text"); } 我唯一的想法是阅读整个文件并数一数行。有更好的解决方案吗?直线的定义 文件中行索引和更具体地说行的定义由\n字符表示。通常(在Wind
int i;
using (StreamWriter s = new StreamWriter("myfilename",true) {
i= s.Index(); //or something that works.
s.WriteLine("text");
}
我唯一的想法是阅读整个文件并数一数行。有更好的解决方案吗?直线的定义
文件中行索引
和更具体地说行
的定义由\n
字符表示。通常(在Windows moreso上)这也可以前面加回车符\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);
}
@雷内:复制品似乎是关于streamreaders的,而不是StreamWriter,关于这个问题的答案在这里的应用并不明显…@Chris-hmm,这是真的,我找不到另一个复制品。重新打开并编辑为什么不能执行
i++代码>而不是i=s.Index()代码>?或者您也在您的文本中写入\r\n?@rene:注意,编写者正在添加,因此op可能需要知道已经存在多少行才能进行自己的跟踪。那就有点死胡同了。他们仍然需要StreamReader,或者至少读取文件中已有的内容。
var numberOfLines = File.ReadAllLines(filePath).Length;