在文件流中移动位置(C#)

在文件流中移动位置(C#),c#,filestream,C#,Filestream,我有一个像这样的txt文件 #header1 #header2 #header3 .... #headerN ID Value Pvalue a 0.1 0.002 b 0.2 0.002 ... 我的代码将尝试解析 FileStream fs = new FileStream(file, FileMode.Open, FileMode.Read); ...... Table t = Table.Load(fs); 我想要的是将流的开始位置设置在“ID”之前,这样我就可以将流提供给代

我有一个像这样的txt文件

#header1
#header2
#header3
....
#headerN
ID Value Pvalue
a  0.1  0.002
b  0.2  0.002
...
我的代码将尝试解析

FileStream fs = new FileStream(file, FileMode.Open, FileMode.Read);
......
Table t = Table.Load(fs);
我想要的是将流的开始位置设置在“ID”之前,这样我就可以将流提供给代码并创建一个新表。但我不确定正确的方法是什么。 提前感谢

尝试此代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication57
{
    class Program
    {
        const string file = "";
        static void Main(string[] args)
        {
            FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
            StreamReader reader = new StreamReader(fs);
            string inputline = "";
            State state = State.FIND_HEADER;
            while((inputline = reader.ReadLine()) != null)
            {
                switch (state)
                {
                    case State.FIND_HEADER:
                        if (inputline.StartsWith("#header"))
                        {
                            state = State.READ_TABLE;
                        }
                        break;
                    case State.READ_TABLE:
                        Table t = Table.Load(fs);
                        break;
                }
            }
        }
        enum State
        {
            FIND_HEADER,
            READ_TABLE
        }

    }
}

理想情况下,您应该转换
Table.Load
以获取
IEnumerable
或至少一个
流阅读器
,而不是原始

如果这不是一个选项,您可以将整个文件读入内存,跳过其标题,并将结果写入
MemoryStream

MemoryStream stream = new MemoryStream();
using (var writer = new StreamWriter(stream, Encoding.UTF8);
    foreach (var line in File.ReadLines(fileName).SkipWhile(s => s.StartsWith("#"))) {
        writer.WriteLine(line);
    }
}
stream.Position = 0;
Table t = Table.Load(stream);

标题大小是否固定?如果流的大小是固定的,您可以设置流的位置,例如s.position=20@SvenB:标题大小为flexibleSave position,使用
StreamReader.ReadLine
检查是否有其他标题,如果是循环,如果没有,将位置设置回原来的位置,然后
Table.Load()
No.not是不需要的。用户希望开始读取ID行。因此,代码将读取“#header”之后的第行,并获取下一行。