C# StreamReader marking question
What I am trying to do is remember where I am in an input stream and later go back there. It is very simple in java using mark() and reset(), but I do not know how to make possible this in c#. There is n开发者_如何学运维o such method.
for example
public int peek()
{
try
{
file.x; //in java file.mark(1)
int tmp = file.read();
file.+ //in java file.reset();
return tmp;
}
catch (IOException ex) {}
return 0;
}
Indeed there isn't that I know of. However you could use something like a Stack and simply Push() and Pop() off this to go up and down your markers in order:
FileStream file = new FileStream(...);
try {
Stack<long> markers = new Stack<long>();
markers.Push(file.Position);
file.Read(....);
file.Seek(markers.Pop(),SeekOrigin.Begin);
} finally {
file.Close();
}
Another idea based on a Dictionary:
FileStream file = new FileStream(...);
try {
Dictionary<string,long> markers = new Dictionary<string,long>();
markers.Add("thebeginning",file.Position);
file.Read(....);
file.Seek(markers["thebeginning"],SeekOrigin.Begin);
} finally {
file.Close();
}
If it is a StreamReader
you are using, you have to keep in mind that it is not exactly a Stream
itself, but you can access its BaseStream
property:
StreamReader reader = new StreamReader("test.txt");
Stream stream = reader.BaseStream;
It will give you your current position in the stream:
long pos = stream.Position;
And it will allow you to move back there:
stream.Seek(pos, SeekOrigin.Begin);
精彩评论