need help converting stream to byte array.

Stream ReceiveStream = myWebResponse.GetResponseStream();

i am using this stream and need to convert it to a byte array. i have to pass the byte array to another function ao i need the stream converted whole to byte array and the size of data received in stream is variable.
so can any1 please give me a code to convert this.
LVL 2
Viraj_KanwadeAsked:
Who is Participating?
 
CeiledCommented:
The cast fails because WebResponse doesn't return a MemoryStream -- for an HTTP response, it actually returns a System.Net.ConnectStream, which is internal to System.dll. You don't want to rely on that. All you need to care about is that it's a Stream.

      using (Stream s = myWebResponse.GetResponseStream())
      {
            // Since we don't know how many bytes there will be,
            // use a dynamic list to store them
            ArrayList byteList = new ArrayList();

            BinaryReader reader = new BinaryReader(s);
            int totalLength = 0;
            byte[] bytes;

            // Keep reading until the reader returns 0 bytes
            while ((bytes = reader.ReadBytes(1024)).Length > 0)
            {
                  byteList.Add(bytes);
                  totalLength += bytes.Length;
            }

            // Create a byte array to store the final result
            bytes = new byte[totalLength];
            int position = 0;

            // Cycle through the list of byte arrays we read in
            // and copy each in turn to the final result
            foreach (byte[] b in byteList)
            {
                  Array.Copy(b, 0, bytes, position, b.Length);
                  position += b.Length;
            }
      }

At this point, "bytes" contains the bytes you want. A simpler (code-wise) solution would be to create a StreamReader instead of a BinaryReader, use ReadToEnd() to grab the entire string, then use an Encoding object to get the bytes back, but this requires knowing the encoding of the source stream and the encoding that the code you pass the array to wants, so it's not quite as robust. Unfortunately, I couldn't find a binary equivalent of TextReader.ReadToEnd(), but the code above is basically what it would look like.
0
 
wishguitarCommented:
MemoryStream ReceiveStream = (MemoryStream)myWebResponse.GetResponseStream();
Byte [] bytes = ReceiveStream.ToArray();
0
 
Viraj_KanwadeAuthor Commented:
MemoryStream ReceiveStream = (MemoryStream)myWebResponse.GetResponseStream();

on this i get a >> specified cast is not valid << exception
is there any other way or some changes needed to the above code
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.