将CSV文件中的行跳过到某个单词C#

skipping Rows in a CSV file to a certain word C#

我是 C# 编码的新手,我真的试图在任何论坛中找到答案。我正在使用 CSVHelper 读取 CSV 文件,我想从文件开头跳过一定数量的行到某个单词。现在我的代码给出了以下错误信息: System.ObjectDisposedException:“无法从关闭的 TextReader 中读取。”请帮助我:

 private void cmdLoad_Click(object sender, EventArgs e)
    {
        OpenFileDialog OFDReader = new OpenFileDialog()
        { };
        if (OFDReader.ShowDialog() == DialogResult.OK)
        {

            txtbox.Text = OFDReader.FileName;
        }
        var config = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            Delimiter = ";", // Set delimiter
            HasHeaderRecord = true,
            //ShouldSkipRecord = (row) => row.Record[0].Contains("Date/Time"),
        };
        
        using (var reader = new StreamReader(OFDReader.FileName))
        using (var csv = new CsvReader(reader, config))
        {               
           //search for Line to start reader
           string record = "Date/Time";

            while (csv.Read())
            {
                if (csv.Read().Equals(record))
                {
                    csv.Read();
                    csv.ReadHeader();
                    break;
                }
                using (var dr = new CsvDataReader(csv))
                {
                    var dt = new DataTable();
                    dt.Load(dr);
                    dataGridView1.DataSource = dt; // Set datagridview source to datatable
                }
            }
        }
    }
}

}

我相信当您找到“Date/Time”文本时,您只需要跳出 while (csv.Read()) 即可。 CsvReader 将从那里完成剩下的工作。

var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
     Delimiter = ";", // Set delimiter
     HasHeaderRecord = true
};

using (var reader = new StreamReader(OFDReader.FileName))
using (var csv = new CsvReader(reader, config))
{
    //search for Line to start reader
    string record = "Date/Time";

    while (csv.Read())
    {
        if (csv.Context.Parser.RawRecord.Trim() == record)
        {
            break;
        }                           
    }
    using (var dr = new CsvDataReader(csv))
    {
        var dt = new DataTable();
        dt.Load(dr);
        dt.Dump();
    }
}