C# Downloading website into string using C# WebClient or HttpWebRequest

1st Method............
----------------------------------------
public void ReadPage()
    {
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create( "https://www.kickass.to/");
        req.Method = "GET";
        req.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))";
   

        string source;
        var response = req.GetResponse();

        var stream = response.GetResponseStream();
        try
        {
            if (response.Headers.AllKeys.Contains("Content-Encoding")
                && response.Headers["Content-Encoding"].Contains("gzip"))
            {
                stream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress);
            }

            using (StreamReader reader = new StreamReader(stream))
            {
                source = reader.ReadToEnd();
            }
        }
        finally
        {
            if (stream != null)
                stream.Dispose();
        }

        Response.Write(source);
    }
------------------------------

2nd Method....
----------------------------

public void ReadPage()
    {
        string result = null;
       
        WebResponse response = null;
        StreamReader reader = null;

        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.kickass.to/");
            request.Method = "GET";
            response = request.GetResponse();
            Encoding  e = Encoding.UTF8;
       
            reader = new StreamReader(response.GetResponseStream(), e);
            result = reader.ReadToEnd();
        }
        catch (Exception ex)
        {
            // handle error
            Response.Write(ex.Message);
        }
        finally
        {
            if (reader != null)
                reader.Close();
            if (response != null)
                response.Close();
        }
    }

Comments

Popular posts from this blog

Executing PowerShell scripts from C#

HOW TO Use the NumericUpDown Control

Exposing Agile Software Development Myths