Reading data from a website using C#

后端 未结 4 1722
终归单人心
终归单人心 2020-12-13 05:15

I have a webpage which has nothing on it except some string(s). No images, no background color or anything, just some plain text which is not really that long in length.

4条回答
  •  执笔经年
    2020-12-13 05:31

    The WebClient class should be more than capable of handling the functionality you describe, for example:

    System.Net.WebClient wc = new System.Net.WebClient();
    byte[] raw = wc.DownloadData("http://www.yoursite.com/resource/file.htm");
    
    string webData = System.Text.Encoding.UTF8.GetString(raw);
    

    or (further to suggestion from Fredrick in comments)

    System.Net.WebClient wc = new System.Net.WebClient();
    string webData = wc.DownloadString("http://www.yoursite.com/resource/file.htm");
    

    When you say it took 30 seconds, can you expand on that a little more? There are many reasons as to why that could have happened. Slow servers, internet connections, dodgy implementation etc etc.

    You could go a level lower and implement something like this:

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.yoursite.com/resource/file.htm");
    
    using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8))
    {
        streamWriter.Write(requestData);
    }
    
    string responseData = string.Empty;
    HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
    using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        responseData = responseReader.ReadToEnd();
    }
    

    However, at the end of the day the WebClient class wraps up this functionality for you. So I would suggest that you use WebClient and investigate the causes of the 30 second delay.

提交回复
热议问题