Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read second line and save it from txt C#

Tags:

c#

What I have to do is read only the second line in a .txt file and save it as a string, to use later in the code.

The file name is "SourceSetting". In line 1 and 2 I have some words

For line 1, I have this code:

string Location;
StreamReader reader = new StreamReader("SourceSettings.txt");
{
    Location = reader.ReadLine();
}
ofd.InitialDirectory = Location;

And that works out great but how do I make it so that it only reads the second line so I can save it as for example:

string Text
like image 903
Christoph Bethge Avatar asked Sep 10 '15 11:09

Christoph Bethge


3 Answers

You can skip the first line by doing nothing with it, so call ReadLine twice:

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

Another way is the File class that has handy methods like ReadLines:

string secondLine = File.ReadLines("SourceSettings.txt").ElementAtOrDefault(1);

Since ReadLines also uses a stream the whole file must not be loaded into memory first to process it. Enumerable.ElementAtOrDefault will only take the second line and don't process more lines. If there are less than two lines the result is null.

like image 102
Tim Schmelter Avatar answered Nov 09 '22 09:11

Tim Schmelter


Update I'd advice to go with Tim Schmelter solution.

When you call ReadLine - it moves the carret to next line. So on second call you'll read 2nd line.

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;

Don't forget about using.

Or an example how to do this vi ReadLines of File class if you need just one line from file. But solution with ElementAtOrDefault is the best one as Tim Schmelter points.

var Text = File.ReadLines(@"C:\Projects\info.txt").Skip(1).First()

The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.

So it doesn't read all lines into memory in comparison with ReadAllLines.

like image 39
Artiom Avatar answered Nov 09 '22 08:11

Artiom


The line could be read using Linq as follows.

var SecondLine = File.ReadAllLines("SourceSettings.txt").Skip(1).FirstOrDefault();
like image 3
Codor Avatar answered Nov 09 '22 08:11

Codor