storing an HttpWebResponse to a byte array

D

Dunc

Hi,

I've got an HttpWebResponse object, all working fine. I'm getting the
underlying stream and currently writing it to a file using the ReadToEnd()
method. All happy.

I want to do a bit of manipulation before writing this to the disk; can
anyone point me in the right direction of how to copy it to a byte array so
I can make my mods before writing it to the disk?

Thanks in advance,

Dunc

---/ snip /---

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strRemoteURI);

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,
System.Text.Encoding.Unicode);
StreamWriter writeStream = new StreamWriter("_" + strFileName, false,
System.Text.Encoding.Unicode);

writeStream.Write(readStream.ReadToEnd());
writeStream.Flush();

response.Close();
readStream.Close();
writeStream.Close();
 
L

Lubo¹ ©lapák

You can use class
System.Convert

byte[] cipherBytes = Convert.FromBase64String(inputString);

and Back:

string s = System.Text.Encoding.UTF8.GetString(cipherBytes);
 
J

Joerg Jooss

Dunc said:
Hi,

I've got an HttpWebResponse object, all working fine. I'm getting the
underlying stream and currently writing it to a file using the
ReadToEnd() method. All happy.

I want to do a bit of manipulation before writing this to the disk;
can anyone point me in the right direction of how to copy it to a
byte array so I can make my mods before writing it to the disk?

Copy the received data to a MemoryStream:

WebRequest request = WebRequest.Create(http://host/path/to/page.htm);

MemoryStream memoryStream = new MemoryStream(0x10000);

using (Stream responseStream = request.GetResponse().GetResponseStream()) {
byte[] buffer = new byte[0x1000];
int bytes;
while ((bytes = responseStream.Read(buffer, 0, buffer.Length)) > 0) {
memoryStream.Write(buffer, 0, bytes);
}
}

// If you cannot manipulate the MemoryStream directly, you can obtain a byte
array
byte[] response = memoryStream.ToArray();

Cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top