Convert to Stream from a Url

I ended up doing a smaller version and using WebClient instead the old Http Request code:

private static Stream GetStreamFromUrl(string url)
{
    byte[] imageData = null;

    using (var wc = new System.Net.WebClient())
        imageData = wc.DownloadData(url);

    return new MemoryStream(imageData);
}

The current answer is missing an example in how to use GetResponseStream()

Here is an example

    // Creates an HttpWebRequest with the specified URL.
    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    // Sends the HttpWebRequest and waits for the response.         
    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
    // Gets the stream associated with the response.
    Stream receiveStream = myHttpWebResponse.GetResponseStream();
    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
    // Pipes the stream to a higher level stream reader with the required encoding format.
    StreamReader readStream = new StreamReader( receiveStream, encode );
Console.WriteLine("\r\nResponse stream received.");
    Char[] read = new Char[256];
    // Reads 256 characters at a time.
    int count = readStream.Read( read, 0, 256 );
    Console.WriteLine("HTML...\r\n");
    while (count > 0)
        {
            // Dumps the 256 characters on a string and displays the string to the console.
            String str = new String(read, 0, count);
            Console.Write(str);
            count = readStream.Read(read, 0, 256);
        }
    Console.WriteLine("");
    // Releases the resources of the response.
    myHttpWebResponse.Close();
    // Releases the resources of the Stream.
    readStream.Close();

For more details see - https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebresponse.getresponsestream?view=net-5.0


You don't need to create a StreamReader there. Just return aResponse.GetResponseStream();. The caller of that method will also need to call Dispose on the stream when it's done.

Tags:

C#

Stream