Posts tagged ‘URL’

C# download web page

I’m sure you had the need sometime to download the content of a web page to be able to analyze it or work with the content. Here is a code snippet just for you, we will use simple http GET for the specified URL.

public static string getWebPage(string psUrl)
{
    WebResponse result = null;
    string sRet = string.Empty;

    try
    {
        WebRequest req = WebRequest.Create(psUrl);
        req.Method = “GET”;
        req.Timeout = 3 * 1000// 3 secs
        // Explicit no caching, usually this is the default
        req.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);

        // Has to process the results if the responding service is spitting it out
        result = req.GetResponse();
        Stream ReceiveStream = result.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding(“utf-8”);
        StreamReader sr = new StreamReader(ReceiveStream, encode);
        // in case the caller is interested
        sRet = sr.ReadToEnd();
    }
    finally
    {
        if (result != null) result.Close();
    }

    return sRet;
}

Image from URL in C#

Here is how you can retrieve a image from a webserver. You only need to know the specific URL, the function does the rest and returns Image object.

// Get image from the given Url
// returns the image or null if not found
public static Image getUrlImage(string psUrl)
{
    WebResponse result = null;
    Image rImage = null;
   
    try
    {
        WebRequest request = WebRequest.Create(psUrl);
        byte[] rBytes;

        // Get the content
        result = request.GetResponse();
        Stream rStream = result.GetResponseStream();

        // Bytes from address
        using( BinaryReader br = new BinaryReader(rStream))
        {
            // Ask for bytes bigger than the actual stream
            rBytes = br.ReadBytes(1000000);
            br.Close();
        }
        // close down the web response object
        result.Close();

        // Bytes into image
        using( MemoryStream imageStream = new MemoryStream(rBytes, 0, rBytes.Length))
        {
            imageStream.Write(rBytes, 0, rBytes.Length);
            rImage = Image.FromStream(imageStream, true);
            imageStream.Close();
        }

    }
    catch (Exception ex)
    {
        Console.WriteLine( “error=” + ex );
    }
    finally
    {
        if (result != null) result.Close();
    }

    return rImage;
}