Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset position in StringReader to begining of String?

I have the following code:

StringReader contentReader = new StringReader(this.dataContent.ToString());

After I parse my DataContent, I need to reset the poistion of the contentReader to begining of the string. How do I do it? I dont see a set poistion option in StringReader

like image 410
savi Avatar asked Dec 11 '22 05:12

savi


2 Answers

Set it to a new instance of StringReader. I don't believe you can change the position of an existing one.

contentReader = new StringReader(this.dataContent.ToString());

like image 88
MatthewHagemann Avatar answered Mar 02 '23 23:03

MatthewHagemann


Another option would be to load the string into a MemoryStream then use a StreamReader to iterate over it. MemoryStream definitely supports position resets on a memory stream.

String data = "Hello! My name it Inigo Montoya.";
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(data)))
{
    using (StreamReader reader = new StreamReader(stream))
    {
        // Do your parsing here using the standard StreamReader methods.
        // They should be fairly comparable to StringReader.

        // When all done, reset stream position to the beginning.
        stream.Seek(0, SeekOrigin.Begin);
    }
}
like image 30
Sam Axe Avatar answered Mar 03 '23 01:03

Sam Axe