How can i download a website content to a string?

后端 未结 3 1662
庸人自扰
庸人自扰 2020-12-21 10:51

I tried this and i want that the source content of the website will be download to a string:

public partial class Form1 : Form
    {
        WebClient client         


        
相关标签:
3条回答
  • 2020-12-21 10:59

    If you are using .Net 4.5,

    public async void Downloader()
    {
        using (WebClient wc = new WebClient())
        {
            string page = await wc.DownloadStringTaskAsync("http://chatroll.com/rotternet");
        }
    }
    

    For 3.5 or 4.0

    public void Downloader()
    {
        using (WebClient wc = new WebClient())
        {
            wc.DownloadStringCompleted += (s, e) =>
            {
                string page = e.Result;
            };
            wc.DownloadStringAsync(new Uri("http://chatroll.com/rotternet"));
        }
    }
    
    0 讨论(0)
  • 2020-12-21 11:12

    Using WebRequest:

    WebRequest request = WebRequest.Create(url);
    request.Method = "GET";
    WebResponse response = request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);
    string content = reader.ReadToEnd();
    reader.Close();
    response.Close();
    

    You can easily call the code from within another thread, or use background worer - that will make your UI responsive while retrieving data.

    0 讨论(0)
  • 2020-12-21 11:24

    No need for async, really:

    var result = new System.Net.WebClient().DownloadString(url)
    

    If you don't want to block your UI, you can put the above in a BackgroundWorker. The reason I suggest this rather than the Async methods is because it is dramatically simpler to use, and because I suspect you are just going to stick this string into the UI somewhere anyway (where BackgroundWorker will make your life easier).

    0 讨论(0)
提交回复
热议问题