-1

I want to read a line from a text file, except that I want to specify the line to read.

I've tried:

using (StreamReader reader = new StreamReader(@"C:\Program Files\TTVB\Users.txt"))

            {
                text = reader.ReadLine(acctMade);
            }

acctMade is an int.

This returns:

No overload for method 'ReadLine' takes 1 arguments

Minicl55
  • 947
  • 5
  • 14
  • 21
  • Use `File.ReadAllLines` (which will give you an array), and then access the line via the correct array index. `string[] text = File.ReadAllLines(); string desiredLine = text[acctMade];` – Tim Jul 27 '13 at 01:06
  • How big is the file ? – Prix Jul 27 '13 at 01:08
  • Only a few kilobytes. Tim, ReadAllLines doesn't exist. – Minicl55 Jul 27 '13 at 01:09
  • @Minicl55 - I edited my comment to `File.ReadAllLines` - to do this you'll need to use `File` instead of `StreamReader`. See [File.ReadAllLines](http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx) – Tim Jul 27 '13 at 01:10
  • If you do end up with a large file, you could seek to the end of the file then read backwards until you find a newline(depending on character set) then read that to the end. – user1132959 Jul 27 '13 at 01:14

2 Answers2

2

If the file is not that big, you can use File.ReadAllLines to put the file into a array of strings:

string[] lines = File.ReadAllLines(@"C:\Program Files\TTVB\Users.txt");
Console.WriteLine(lines[acctMade]);

You need to use using System.IO; at the top of your code or use System.IO.File.ReadAllLines in order for it to be usable.

Prix
  • 19,417
  • 15
  • 73
  • 132
2

A variety of ways: Read certain line in a text file (CodeProject

A simple way using StreamReader:

string GetLine(string fileName, int line)
{
   using (var sr = new StreamReader(fileName)) {
       for (int i = 1; i < line; i++)
          sr.ReadLine();
       return sr.ReadLine();
   }
}

Snippet from: How do I read a specified line in a text file?

For a more efficient but complex way:

Community
  • 1
  • 1
jrbeverly
  • 1,611
  • 14
  • 20