Search code examples
c#streamreader

StreamReader shows content on WriteLine function but return empty if using it in a variable


Can somebody help me solving this? When I use the reader on WriteLine it writes the message perfectly, but when I try to save as a variable too, it return an empty string. I'm doing this because I want to save the log on a file afterwards.

using (var stream = ex.Response.GetResponseStream())
                using (var reader = new StreamReader(stream, Encoding.UTF8))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    Console.WriteLine("Username: " + usernames[i]);
                    Console.WriteLine(reader.ReadToEnd());
                    content = reader.ReadToEnd().ToString();
                    Console.WriteLine(content);
                    Console.WriteLine("URL: https://api.bitbucket.org/2.0/users/" + usernames[i] + "\n");

Solution

  • A reader reads in one direction: forward. If you want to read the same value twice, you have to back up and read it again.

    Modify your code as follows:

    using (var stream = ex.Response.GetResponseStream())
    using (var reader = new StreamReader(stream, Encoding.UTF8))
    {
        stream.Seek(0, SeekOrigin.Begin);
        Console.WriteLine("Username: " + usernames[i]);
        Console.WriteLine(reader.ReadToEnd());
    
        stream.Seek(0, SeekOrigin.Begin);
        content = reader.ReadToEnd().ToString();
        Console.WriteLine(content);
        Console.WriteLine("URL: https://api.bitbucket.org/2.0/users/" + usernames[i] + "\n");