I have to display on the screen a specific line of a .txt file, in C#. My code so far is this:
while (!file.EndOfStream)
{
counter++;
if (counter == 4) {
line = file.ReadLine();
System.Console.WriteLine(line);
}
}
I have also tried with this code but I get the first line:
while (!file.EndOfStream)
{
line = file.ReadLine();
//System.Console.WriteLine(line);
if (++counter ==4) break;
}
Also know to see if a specific line could be read but detecting a string of characters.
Properties:
Name=X
Path=X
Version=1.000
The text file looks something like this, I need to read the version, it's just for testing.
I would do it like this if there are not too many lines:
To expand on the answer, if you didn't know exactly what line the text you need to search for is on, you could do it like this:
If you need to search for a specific row in a text file, it's best to use
ReadAllLines
Veelicus as well recommended in his answer. That way you havestring[]
the whole file and it is easier to manipulate it.As for searching for a specific text, you can make use of LINQ in combination with
Contains
orStartsWith
: