C# C# Streams and Data Processing Streaming Data on the Net WebClient

Daniel Tkach
Daniel Tkach
7,607 Points

Why not skip the MemoryReader and the rest and return right away the byte[]?

I wonder why not convert the byte[] to string and return that, or just return the byte[].

What are we achieving by amassing the bytes with these lines:

        using(var stream = new MemoryStream(googleHome))
        using(var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }

We put the bytes[] into a MemoryStream so that then we get this stream and put it in the reader to then return what, a string from the ReadToEnd() method. All this does not make any sense for me lol

3 Answers

James Churchill
STAFF
James Churchill
Treehouse Teacher

Daniel,

Thanks for your question!

I believe that Carling is converting the byte array to a string in order to output the web page's HTML to the console. If you pass the byte array directly to the Console.WriteLine method, you get System.Byte[] as the output.

But you are correct in that you can convert the byte array to a string without using the stream/reader combo. In fact, there are many ways in .NET to do this; here's just one example:

WebClient webClient = new WebClient();
byte[] data = webClient.DownloadData("https://www.google.com");
string stringData = System.Text.Encoding.Default.GetString(data);
Console.WriteLine(stringData);

However, one advantage to using Carling's approach is that we don't need to know the encoding of the string data in order to do the conversion. That may or may not impact your results, so your mileage might vary.

Thanks ~James

Daniel Tkach
Daniel Tkach
7,607 Points

Amazing James, thank you so much for the explanation. I'm about to finish the C# track and I'm looking forward to starting your lessons! Please do more, ASP is what interests me the most at the moment. See you around.

James Churchill
James Churchill
Treehouse Teacher

Thanks Daniel! I'm working on a new ASP.NET MVC related course now... "Using Entity Framework with ASP.NET MVC" and will then move on to courses on Web API and Identity. So, lots of great content coming in the coming months.

David Lin
David Lin
35,839 Points

A more direct alternative to get a string as the response is to use WebClient's DownloadString method.

        public static string GetStringResponse(string url)
        {
            string response = "";
            using(var webClient = new WebClient())
            {
                response = webClient.DownloadString(url);
            }
            return response;
        }
Daniel Tkach
Daniel Tkach
7,607 Points

Wow thanks for letting me know. Yeah I think I saw the first one planned for next month. This eases my anxiety a bit ha!