Question with C # StreamReader

What I'm trying to do is remember where I am in the input stream, and then return there. It is very simple in java using labels () and reset (), but I don't know how to make this possible in C #. There is no such method.

eg

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;
}
+3
source share
2 answers

Verily, I do not know this. However, you can use something like Stack and just Push () and Pop () from 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 dictionary based idea:

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();
}
+5
source

If you use StreamReader, you should keep in mind that this is not quite like Stream, but you can access the property BaseStream:

StreamReader reader = new StreamReader("test.txt");
Stream stream = reader.BaseStream;

This will give you the current position in the stream:

long pos = stream.Position;

And this will allow you to return there:

stream.Seek(pos, SeekOrigin.Begin);
0
source

All Articles