Moving the file cursor up lines?

折月煮酒 提交于 2019-12-20 02:43:16

问题


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, and I want to read over a certain number of lines in the file a certain number of times, however, There doesn't seem to be any way to move the file cursor to certain positions in the file.

(No code because I have no clue how I would go about writing something like this)


回答1:


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<int> 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.




回答2:


Stream.Seek() (MSDN docs) is what you need, but that's an absolute position in the file, and has no notion of line breaks.

I'd prefer to read the lines into a collection memory, then iterate over the collection in memory as often as you like before loading the next few lines in. In fact, unless you're talking gigglebytes of data, just read all the lines in as string objects in a List<string> and do whatever you need with it.




回答3:


there is no way to position to an exact line... only to absolute or relative byte within the file... if you need to position to a line you will need to implement that yourself - either by loading the file into a string[] (not recommended for big files!) or by scanning the file and building an index containing the absolute position for each line so you can later on use that index to Seek to the needed line...



来源:https://stackoverflow.com/questions/8769609/moving-the-file-cursor-up-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!