Read bytes from GetResponseStream.

  • Thread starter Thread starter SK
  • Start date Start date
S

SK

Hi,

I am not able to convert the response stream from HttpWebResponse into bytes
properly.

Here is the relevent code -

HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream ();

// Pipes the stream to a higher level stream reader with the required
// encoding format.
StreamReader readStream = new StreamReader (receiveStream, Encoding.ASCII);

string receivestream = readStream.ReadToEnd ();
// rgBuffer is a big enough byte array.
rgBuffer = Encoding.ASCII.GetBytes (receivestream) ;

response.Close ();
readStream.Close ();

I see a problem in the way I am converting my response to bytes. rgBuffer
doesn't carry correct values.
What is the correct way?

Thanks,
SK
 
SK said:
I am not able to convert the response stream from HttpWebResponse into bytes
properly.

The response stream is in bytes already - there's no conversion needed.
The problem is that you're converting it from bytes to text and back in
a lossy way.
Here is the relevent code -

HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream ();

// Pipes the stream to a higher level stream reader with the required
// encoding format.
StreamReader readStream = new StreamReader (receiveStream, Encoding.ASCII);

string receivestream = readStream.ReadToEnd ();
// rgBuffer is a big enough byte array.
rgBuffer = Encoding.ASCII.GetBytes (receivestream) ;

response.Close ();
readStream.Close ();

I see a problem in the way I am converting my response to bytes. rgBuffer
doesn't carry correct values.
What is the correct way?

You're converting the bytes to ASCII and back again. ASCII only has 128
values. Fundamentally, this is binary data and you have no good reason
to convert it to text and back again.

See http://www.pobox.com/~skeet/csharp/unicode.html
and
http://www.pobox.com/~skeet/csharp/readbinary.html
for more information - the latter has some code called ReadFully which
should give you the binary equivalent of StreamReader.ReadToEnd.
 
Jon Skeet said:
The response stream is in bytes already - there's no conversion needed.
The problem is that you're converting it from bytes to text and back in
a lossy way.


You're converting the bytes to ASCII and back again. ASCII only has 128
values. Fundamentally, this is binary data and you have no good reason
to convert it to text and back again.

See http://www.pobox.com/~skeet/csharp/unicode.html
and
http://www.pobox.com/~skeet/csharp/readbinary.html
for more information - the latter has some code called ReadFully which
should give you the binary equivalent of StreamReader.ReadToEnd.
Cool..works after making changes like ReadFully :-)
Thank you,
SK
 
Back
Top