文本文件:逐行读取C# [英] text file: Reading line by line C#
问题描述
所以,假设我有一个20行的文本文件,每行文本不同.我希望能够有一个包含第一行的字符串,但是当我执行NextLine()时;我希望它成为下一行.我试过了,但似乎不起作用:
So, let's say i have a text file with 20 lines, with on each line different text. i want to be able to have a string that has the first line in it, but when i do NextLine(); i want it to be the next line. I tried this but it doesn't seem to work:
string CurrentLine;
int LastLineNumber;
Void NextLine()
{
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
CurrentLine = file.ReadLine(LastLineNumber + 1);
LastLineNumber++;
}
我该怎么做?预先感谢.
How would i be able to do this? Thanks in advance.
推荐答案
通常,最好以某种方式设计此方式以使文件保持打开状态,而不是每次都尝试重新打开该文件.
In general, it would be better if you could design this in a way to leave your file open, and not try to reopen the file each time.
如果这不切实际,则需要多次调用 ReadLine
:
If that is not practical, you'll need to call ReadLine
multiple times:
string CurrentLine;
int LastLineNumber;
void NextLine()
{
// using will make sure the file is closed
using(System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt"))
{
// Skip lines
for (int i=0;i<LastLineNumber;++i)
file.ReadLine();
// Store your line
CurrentLine = file.ReadLine();
LastLineNumber++;
}
}
请注意,这可以通过 File.ReadLines
进行简化:
Note that this can be simplified via File.ReadLines
:
void NextLine()
{
var lines = File.ReadLines("C:\\test.txt");
CurrentLine = lines.Skip(LastLineNumber).First();
LastLineNumber++;
}
这篇关于文本文件:逐行读取C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!