Reset StreamReader for several uses of XmlReader.Read ()

I would like to reuse the StreamReader associated with the XML file for .Read () - Call from System.Xml.XmlReader.

I basically put together a small extension method containing 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 remains unchanged throughout the session.

The first time this works very well, but if I use this method a second time, I get a System.Xml-Exception. Is there a way to effectively "reset" StreamReader?

Thanks,

Dennis

+4
source share
4 answers

You cannot just change the position in BaseStream , because StreamReader buffers the data from the main stream. It will just ruin the behavior of the StreamReader , nothing good will come of it.

You must delete the old StreamReader and create a new one each time instead.

+5
source

StreamReader not an expensive object to create, so if the underlying stream supports positioning, you just need to create a new StreamReader on it every time.

+2
source

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

 reader.Close(); 

Your reader may not close correctly, which causes problems with the next reading.

0
source

Since this is buffering, you need to discard the buffer in addition to flushing the position.

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

I did this when I want to find out how many lines are in the file I'm going to parse (lines from the 1st pass, 2nd analysis and analysis of the results).

0
source

All Articles