-2

I've been having some problems extracting particular lines in a txt file. I'm using the file to store user names for a login program.

The program will know what line to go to in the text file but I don't know how to actually get the wanted line out and put the resulting string into a variable.

Code I'm using to pull file into a variable is:

string usernameFile = System.IO.File.ReadAllText(@"Usernames.txt");

My real problem is that code two lines below doesn't work in my visual studios community version 2017:

File.ReadLine

I don't know if I need to install something else onto my visual studios but any method to be able to read a particular line of a txt file will be fine.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Scott Preen
  • 57
  • 3
  • 8
  • There's no such method as `File.ReadLine()` in the .NET library, so it's not surprising that it doesn't work. – itsme86 Oct 05 '17 at 23:00
  • 1
    Possible duplicate of [How do I read a specified line in a text file?](https://stackoverflow.com/questions/1262965/how-do-i-read-a-specified-line-in-a-text-file) – Lance U. Matthews Oct 05 '17 at 23:34

2 Answers2

1

Use File.ReadAllLines instead. That gives you an array of strings, one for each line.

string[] lines = File.ReadAllLines("Usernames.txt");
string username = lines[2]; // or whatever.
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
0

You can use LINQ to avoid reading the entire file:

var line = File.ReadLines("Usernames.txt").Skip(2).First();
itsme86
  • 19,266
  • 4
  • 41
  • 57