Groups | Blog | Home
all groups > c# > november 2003 >

c# : How to convert a non-seekable Stream to Byte Array?


Hardy Wang
11/8/2003 10:50:43 PM
Hi all:
The Stream object from WebRequest.GetResponseStream() is non-seekable.
How can I convert this stream to a byte array?

For ordinary Stream (seekable), I can use StreamObject.Read(myByteArray,
0, myLength)

--



WWW: http://hardywang.1accesshost.com
ICQ: 3359839
yours Hardy

Jon Skeet [C# MVP]
11/9/2003 8:35:31 AM
[quoted text, click to view]

You can use that with a non-seekable request too. However, in both
cases you shouldn't ignore the return value - it may well be that you
can't read the whole of the data in one chunk. You should loop until
either you've read everything you need to or you've got to the end of
the stream (where Read will return -1).

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
Hardy Wang
11/9/2003 12:17:34 PM
I tried responseStream.Read(respbuffer,0, respBuffer.Length);

At this point an exception was thrown.

[quoted text, click to view]

Aravind C
11/9/2003 12:44:54 PM
Hi Hardy,

Since the response stream from a web request is a network stream
that does not provide random access (non-seekable), you will need to
copy the response stream to a seekable stream such as a MemoryStream
before you can perform seek operations:

Stream responseStream = webResponse.GetResponseStream();
MemoryStream memStream = new MemoryStream();

byte [] respBuffer = new byte[1024];
try
{
int bytesRead = responseStream.Read(respbuffer,0,
respBuffer.Length);
if(bytesRead > 0)
{
memStream.Write(respBuffer,0,bytesRead);
bytesRead = responseStream.Read(respBuffer,0,
respBuffer.Length);
}
}
finally
{
responseStream.Close();
webResponse.Close();
}

To get the array containing the byte data from the MemoryStream, use the
MemoryStream.GetBuffer() method.

Regards,
Aravind C


[quoted text, click to view]

Jon Skeet [C# MVP]
11/9/2003 5:44:39 PM
[quoted text, click to view]

And what was the exception?

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
Hardy Wang
11/9/2003 8:10:11 PM
Just like something "the stream is not seakable"


[quoted text, click to view]

Jon Skeet [C# MVP]
11/10/2003 8:05:04 AM
[quoted text, click to view]

"Something like" doesn't help much. Could you post a short but
*complete* sample which demonstrates the problem? There should be no
problem just reading from the stream, if you're not actually *trying*
to seek.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
AddThis Social Bookmark Button