Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 no 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;
}
like image 690
Strausa Avatar asked Jul 25 '26 05:07

Strausa


1 Answers

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();
}
like image 105
Lloyd Avatar answered Jul 27 '26 02:07

Lloyd