-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#.

4
  • 1
    What is this code suppose to do? Commented Feb 6, 2014 at 10:45
  • assign example.com url's html or xml source to a string valuable. @MaxMommersteeg Commented Feb 6, 2014 at 10:47
  • possible duplicate of Easiest way to read from a URL into a string in .NET Commented Feb 6, 2014 at 10:50
  • @BardiaHeydari Did you figure it out? Commented Feb 6, 2014 at 11:11

3 Answers 3

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 :).

Sign up to request clarification or add additional context in comments.

3 Comments

I like it! Good for downloading to a string.
What if it needs username and password?
Then use: if (Object.ReferenceEquals(null, WebRequest.DefaultWebProxy.Credentials)) WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials; , code by @Dmitry Bychenko, default credentials will be provided.
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);
  }

Comments

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 :).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.