4

I'd like to re-use a StreamReader I've associated with an XML file for .Read()-Calls from System.Xml.XmlReader.

Basically I've put together a small extension method featuring the following code:

 public static string GetValueByPath(this StreamReader str, string attributeName, params string[] nodes)
    {
        str.BaseStream.Position = 0;
        XmlReader reader = XmlReader.Create(str);
        // Stuff happens here now, not important for the question
    }

The StreamReader calling this extension method stays the same throughout the whole Session.

The first time this works just fine, but if I use this method a second time I receive a System.Xml-Exception. Is there no way to effectively "reset" a StreamReader?

Thanks,

Dennis

Dennis Röttger
  • 1,975
  • 6
  • 32
  • 51

4 Answers4

6

You can't just change the position in the BaseStream, because the StreamReader is buffering the data from the underlying stream. It will just mess with the behavior of the StreamReader, nothing good will come out of it.

You should dispose the old StreamReader and create a new one every time instead.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • Thanks for your answer, I was afraid this'd be the case. You wouldn't perchance know a way to do this inside an ASP Web Application without unnecessarily bloating up the code? – Dennis Röttger Apr 19 '11 at 15:01
  • @Dennis, not sure what you mean... I can't really answer that without seeing your code – Thomas Levesque Apr 19 '11 at 15:52
2

StreamReader is not an expensive object to create, so as long as the underlying stream supports setting the position then you should just create a new StreamReaderon it each time.

Chris Wenham
  • 23,679
  • 13
  • 59
  • 69
1

Since it's buffering, you need to discard the buffer in addition to resetting the position.

            sr.BaseStream.Position = 0;
            sr.DiscardBufferedData();

I've done this when I want to know how many lines are in the file I'm about to parse (1st pass counts lines, 2nd pass parses and stores results).

david
  • 61
  • 4
0

Have you tried adding this to then end of your method?

reader.Close();

Your reader might not be closing correctly which is causing issues with the next read.

cush
  • 283
  • 2
  • 8