Search code examples
c#filestream

Move position in FileStream (C#)


I have a txt file like this

#header1
#header2
#header3
....
#headerN
ID Value Pvalue
a  0.1  0.002
b  0.2  0.002
...

My code will try to parse

FileStream fs = new FileStream(file, FileMode.Open, FileMode.Read);
......
Table t = Table.Load(fs);

what I want is to make the start position of the Stream right before "ID", so I can feed the stream to the code and make a new table. But I am not sure what is the correct way to do it. Thanks in advance


Solution

  • Ideally, you should convert Table.Load to take an IEnumerable<string> or at least a StreamReader, not a raw Stream.

    If this is not an option, you can read the whole file into memory, skip its header, and write the result into 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);