user2788405
user2788405

Reputation: 325

Ignore first 8 lines of txt file when reading ? c#

I want to ignore the part in the blue box and start reading my txt file from the arrow

enter image description here

I'm planning on just looping through first 8 lines and storing them in a junk variable. If I do this will my crusor now be at the 9th line so I can start reading from there? My code's definitely wrong, it doesn't even read the first 8 lines.

private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName));


            for (int i = 0; i < 8; i++)
            {
                string junk = sr.ReadLine();
            }

            sr.Dispose();

        }
    }

Upvotes: 0

Views: 5721

Answers (2)

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

You can use this:

var lines = File.ReadLines(ofd.FileName);

foreach (string line in lines.Skip(8))
    Trace.WriteLine(line);

Because the File.ReadLines returns an IEnumerable<string>, the lines are only loaded when iterated.

More info: File.ReadLines Method http://msdn.microsoft.com/en-us/library/dd383503.aspx

Upvotes: 10

Raphael Lima
Raphael Lima

Reputation: 179

It's a dumb aproach but it works. You have to consume the line.

        StreamReader sr = new StreamReader(@"TextFile1.txt");

        int i = 1;

        while (!sr.EndOfStream)
        {
            if(i > 8)
                Console.WriteLine(sr.ReadLine ());
            sr.ReadLine ();
            i++;
        }

Upvotes: 0

Related Questions