c sharp stream to byte array 1

c sharp stream to byte array

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

Here is what the above code is Doing:
1. It’s creating a new WebRequest object, and setting the URL to the URL of the file you want to download.
2. It’s setting the method to GET, which is the default, but I like to be explicit.
3. It’s calling GetResponse() on the WebRequest object, which returns a WebResponse object.
4. It’s calling GetResponseStream() on the WebResponse object, which returns a Stream object.
5. It’s calling ReadFully() on the Stream object, which returns a byte array.
6. It’s converting the byte array to a string, and returning it.

Similar Posts