读第二行并从txt C#保存

Chr*_*hge 6 c#

我要做的是只读取.txt文件中的第二行并将其保存为字符串,以便稍后在代码中使用.

文件名是"SourceSetting".在第1行和第2行,我有一些话

对于第1行,我有这个代码:

string Location;
StreamReader reader = new StreamReader("SourceSettings.txt");
{
    Location = reader.ReadLine();
}
ofd.InitialDirectory = Location;
Run Code Online (Sandbox Code Playgroud)

这很好但但我如何才能使它只读取第二行,所以我可以保存它,例如:

string Text
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 13

您可以通过不执行任何操作跳过第一行,因此请调用ReadLine两次:

string secondLine:
using(var reader = new StreamReader("SourceSettings.txt"))
{
    reader.ReadLine(); // skip
    secondLine = reader.ReadLine();  
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是File具有方便方法的类ReadLines:

string secondLine = File.ReadLines("SourceSettings.txt").ElementAtOrDefault(1);
Run Code Online (Sandbox Code Playgroud)

由于ReadLines还使用流,因此不得首先将整个文件加载到内存中以进行处理.Enumerable.ElementAtOrDefault只会占用第二行而不处理更多行.如果结果少于两行null.


Art*_*iom 7

更新我建议采用Tim Schmelter解决方案.

当您调用ReadLine时 - 它会将carret移动到下一行.所以在第二次通话时你会看到第二行.

string Location;
using(var reader = new StreamReader("SourceSettings.txt"))
{
    Location = reader.ReadLine(); // this call will move caret to the begining of 2nd line.
    Text = reader.ReadLine(); //this call will read 2nd line from the file
}
ofd.InitialDirectory = Location;
Run Code Online (Sandbox Code Playgroud)

不要忘记使用.

或者如果您只需要文件中的一行,如何执行此vi ReadLines of File类的示例.但Tim Schmelter指出,解决方案ElementAtOrDefault是最好的解决方案.

var Text = File.ReadLines(@"C:\Projects\info.txt").Skip(1).First()
Run Code Online (Sandbox Code Playgroud)

ReadLines和ReadAllLines方法的不同之处如下:使用ReadLines时,可以在返回整个集合之前开始枚举字符串集合; 当您使用ReadAllLines时,必须等待返回整个字符串数组才能访问该数组.因此,当您使用非常大的文件时,ReadLines可以更高效.

因此,与ReadAllLines相比,它不会将所有行读入内存.