-1

This code is written with python:

import urllib3
http = urllib3.PoolManager()
url = "http://www.example.com/"
req = http.request('GET', url)
source = req.dat

I want to know how can I write it with C#.

Max
  • 11,136
  • 15
  • 65
  • 92
Bardia Heydari
  • 737
  • 9
  • 23

3 Answers3

3

Use following code:

using (WebClient client = new WebClient ()) // Use using, for automatic dispose of client
{
    //Get HTMLcode from page
    string htmlCode = client.DownloadString("http://www.example.com");
}

Add reference to System.Net at top of your class:

using System.Net;

But Oliver's answer offers more control :).

Max
  • 11,136
  • 15
  • 65
  • 92
  • 1
    I like it! Good for downloading to a `string`. – Oliver Feb 06 '14 at 10:55
  • What if it needs username and password? – Bardia Heydari Feb 06 '14 at 11:16
  • Then use: `if (Object.ReferenceEquals(null, WebRequest.DefaultWebProxy.Credentials)) WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;` , code by @Dmitry Bychenko, default credentials will be provided. – Max Feb 06 '14 at 11:18
2

It looks like you're downloading a web response. Below is one way to do this:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/");

using (var stream = request.GetResponse().GetResponseStream())
{
   var reader = new StreamReader(stream, Encoding.UTF8);
   var responseString = reader.ReadToEnd();
}

But Max's answer is easier :).

Oliver
  • 8,191
  • 2
  • 31
  • 55
2

If you want just to download from URL you can try using

  String url = @"http://www.example.com/";
  Byte[] dat = null;

  // In case you need credentials for Proxy
  if (Object.ReferenceEquals(null, WebRequest.DefaultWebProxy.Credentials))
    WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;

  using (WebClient wc = new WebClient()) {
    // Seems that you need raw data, Byte[]; if you want String - wc.DownLoadString(url);
    dat = wc.DownloadData(url);
  }
Dmitry Bychenko
  • 149,892
  • 16
  • 136
  • 186