0

I'm using C# and writing a Windows Form application for Windows 7 or Windows 8.

I need to know how to get my app to read a specific line which should be assigned to a specific text box or combo box.

This is the code I have so far.

        using (StreamReader QNARead = new StreamReader(TestPath))
            if (QNARead.Peek() >= 0)
            {
                string Line1 = QNARead.ReadLine();
                QuestionText1.Text = Line1;

                string Line2 = QNARead.ReadLine();
                QuestionText2.Text = Line2;

                string Line3 = QNARead.ReadLine();
                AlternativesList1.Items.Add(Line3);
            }

But with this method I'll have to read a lot of lines, because the line could be the 500th in the text file. (I do know the exact line number, eg. 54).

Revious
  • 7,816
  • 31
  • 98
  • 147

2 Answers2

3

I used once this to read a specific line in a text file:

string filename = "test.txt";
if (File.Exists(filename))
{
    string[] lines = File.ReadAllLines(filename);
    Console.WriteLine(lines[5]);
}

where 5 can be replaced with any line number (zero based).

eMi
  • 5,540
  • 10
  • 60
  • 109
2

Since a file is just a list of bytes, you need to know how far into it to read, to get the line you want.

Unless the lines are fixed (or predictable) lengths, or you have some kind of separate index, you need to read every line up to the one you want. From a code point of view you can make this fairly tidy, for example in Framework 4.0:

string line54 = File.ReadLines(FileName).Skip(53).Take(1).First();

Note that at this point, you're not taking advantage of reading the earlier lines being skipped over, so a more efficient way would be to keep reading in a loop until you reach the last line needed.

Geoff
  • 8,551
  • 1
  • 43
  • 50
  • Thank you so much! This code worked perfectly for me. – Willem Voigt Oct 06 '14 at 16:15
  • @Willem Voigt Sir, the link I provided in the comment section of your question (http://stackoverflow.com/questions/1262965/how-do-i-read-a-specified-line-in-a-text-file) where you said `"I found the above link, but it not help."` shows (I deleted the link after) in the first answer exactly the same as what was posted here. – eMi Oct 06 '14 at 17:16
  • Apologies. I'll blame it on a lack of coffee :) – Willem Voigt Oct 06 '14 at 17:25
  • To ellaborate. I did find the same line of code, but must have read something wrong, because the code did not compile. – Willem Voigt Oct 07 '14 at 06:46
  • Don't worry, its fine :) – eMi Oct 07 '14 at 06:50