Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,
I am running the following code in C#:

WebResponse response = request.GetResponse();

and I want to store/convert the result into the byte array.

Please help me.

Thanks in advance.
Posted
Updated 16-Oct-17 9:27am

Hi,
Try this:
C#
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);
    }
}
catch(Exception ex)
{
    //Handle exception
}
finally
{
    responseStream.Close();
    webResponse.Close();
}


And also view the similar thread[^].


--Amit
 
Share this answer
 
Comments
navyjax2 16-Oct-17 15:03pm    
That will only write a file that's 1 KB or less. Needs a "while" loop, like Solution 2.
C#
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);
}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900