0

我想忽略蓝色框中的部分并从箭头开始读取我的txt文件

在此处输入图像描述

我打算只遍历前 8 行并将它们存储在一个垃圾变量中。如果我这样做,我的光标现在会在第 9 行,这样我就可以从那里开始阅读了吗?我的代码肯定是错误的,它甚至没有读取前 8 行。

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();

        }
    }
4

2 回答 2

10

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

于 2013-09-27T21:34:41.047 回答
0

这是一种愚蠢的方法,但它有效。你必须消耗这条线。

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

        int i = 1;

        while (!sr.EndOfStream)
        {
            if(i > 8)
                Console.WriteLine(sr.ReadLine ());
            sr.ReadLine ();
            i++;
        }
于 2013-09-27T21:39:04.470 回答