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

Aaron Selonke
Aaron Selonke
10,323 Points

Why are we using the MemoryStream?

In the MSDN docs a Memory stream "Creates a stream whose backing store is memory." What does 'backing store' refer to exactly?

In the code from the video the WebClient's DownloadData method returns a byte[] array, that is then used to pass as a parameter to the MemoryStream.... Why are these communicating in byte arrays? I looked at the byte array its a long array of numbers, do those numbers represent the URI or the whole pages, www.google.com

Carling also mentions that when we were using the StreamReader/StreamWriter ealier, we were 'not using a stream directly' as opposed to in the MemoryStream we are using the stream directly...... What does that mean?

Basically wound like to know why we are using the MemoryStream specifically? Why does the MemoryStream take a byte[] array?

Here is the code that brought up the array of questions

var webClient = new WebClient();
            var googleHome = webClient.DownloadData("https://www.google.com");

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

1 Answer

Steven Parker
Steven Parker
203,151 Points

:point_right: The "backing store" is "where the data comes from".

In this case, the stream data is already in memory as a byte array. The numbers are the character codes of the text data that was gathered from the page.

Instead of using the Stream directly, we are using the StreamReader to handle the Stream. We only call the methods of the StreamReader.

A MemoryStream can be constructed in a variety of ways, but by passing a byte array it becomes associated with the data contained in that array.

Aaron Selonke
Aaron Selonke
10,323 Points

That's how I remember it for now, MemoryStream can read a byte array, and StreamReader can read a Stream