Moving the file cursor up lines?

后端 未结 3 577
囚心锁ツ
囚心锁ツ 2021-01-21 01:01

I\'ve googled this like crazy, and I can\'t seem to find any reference at all to this particular type of problem.

I have a StreamReader object with a file,

3条回答
  •  孤独总比滥情好
    2021-01-21 01:35

    You should be able to use

    myStreamReader.BaseStream.Position = desiredPosition;
    myStreamReader.DiscardBufferedData();
    

    to move the stream to a specific place.

    EDIT: The next question is how to find the desiredPosition. Since you want to move the position back through the file, not forward, it follows that you have read each position at some point. You need to keep track of where you are in the stream as you read your lines, and store positions in a List positions. Initially, the list should contain 0 at position zero. As you process lines, add the length of the line plus the size of line break to the list. When you want to go back to line k, positions[k] should have the position you need.

    For example, if your file has the lines below, your encoding uses one character per letter, and the line separator in the file is Windows-style \r\n

    Quick
    brown fox
    jumps over lazy
    dog
    

    then your positions list should have {0, 7, 17, 34} Note that I added 2 on each line for the separator characters.

    P.S. This is an ugly solution, isn't it? If it is any comfort, you are not the first person who ran into it. Here is a somewhat obscene rant from someone who wanted to solve a similar problem back in 2007.

提交回复
热议问题