3

how do i read the second line of text in visual studio 2012 c#

         the txt file

         user123
         **12345**
         asdfd

i want to get the second line in one button1_click and show it to textblock2

i did try learn from here How do I read a specified line in a text file?

and here How to skip first line and start reading file from second line in C#

but no one of these works because theres difference i couldnt apply in my code

any help?

================================================================================= sorry to confusing you all actually im really lacking experience in programming and i hardly know how to use it
right now im using vs2012 in windows8 , is that mean i was coding in winrt?

btw , i appreciate all your help and successfully applying answer to my code this is the actual code

        var file = await ApplicationData.Current.LocalFolder.GetFileAsync(tb1.Text+".txt");
        var line = await FileIO.ReadLinesAsync(file);
        if (tb2.Text == line[2])
        {
            tb3.Text = (line[1]);
        }
Community
  • 1
  • 1
Andy Surya
  • 117
  • 3
  • 9

3 Answers3

6
var desiredText = File.ReadLines("C:\myfile.txt").ElementAt(1);

File.ReadLines() returns an IEnumerable<String> of the lines in a file. The index of the second line is 1. See this.

tallseth
  • 3,635
  • 1
  • 23
  • 24
2

try

var desiredText = File.ReadLines("C:\myfile.txt");
textbox1.text = desiredText[1];
N B
  • 391
  • 3
  • 12
1

Just call a .ReadLine() before you start capturing the content of the file.

Essentially this will make the reader skip the first line of the file and take only the 2nd line and all lines that follow it.

// Try this to take the second line.
string line;
using (var file_read = new StreamReader(your_file))
{
    file_read.ReadLine(); 
    line = file_read.ReadLine();
}
textBox1.Text = line.ToString();
Ortund
  • 8,095
  • 18
  • 71
  • 139
mfatihk
  • 136
  • 2
  • 11