簡體   English   中英

使用C#從網站讀取數據

[英]Reading data from a website using C#

我有一個除了一些字符串之外什么都沒有的網頁。 沒有圖像,沒有背景顏色或任何東西,只是一些長度不是很長的純文本。

我只是想知道,什么是最好的(通過這種方式,我的意思是最快和最有效)的方式來傳遞網頁中的字符串,以便我可以用它來做其他事情(例如在文本框中顯示)? 我知道WebClient,但我不確定它是否會做我想做的事情,而且即使它確實有效,我也不想嘗試它,因為我上次做的時間大約需要30秒一個簡單的操作。

任何想法,將不勝感激。

WebClient類應該能夠處理您描述的功能,例如:

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);

或(進一步由Fredrick在評論中提出建議)

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

當你說花了30秒時,你可以再擴展一下嗎? 關於為什么會發生這種情況的原因有很多。 緩慢的服務器,互聯網連接,狡猾的實施等。

你可以降低一級並實現這樣的事情:

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();
}

但是,在一天結束時,WebClient類會為您包裝此功能。 所以我建議您使用WebClient並調查30秒延遲的原因。

如果您正在下載文本,那么我建議使用WebClient並獲取文本的流讀取器:

        WebClient web = new WebClient();
        System.IO.Stream stream = web.OpenRead("http://www.yoursite.com/resource.txt");
        using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
        {
            String text = reader.ReadToEnd();
        }

如果這需要很長時間,那么它可能是網絡問題或Web服務器上的問題。 嘗試在瀏覽器中打開資源,看看需要多長時間。 如果網頁非常大,您可能希望查看以塊為單位進行流式傳輸,而不是像在該示例中那樣一直讀到最后。 查看http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx以了解如何從流中讀取。

關於建議所以我建議您使用WebClient並調查30秒延遲的原因。

從問題System.Net.WebClient的答案不合理地慢

嘗試設置Proxy = null;

WebClient wc = new WebClient(); wc.Proxy = null;

感謝Alex Burtsev

 WebClient client = new WebClient();
            using (Stream data = client.OpenRead(Text))
            {
                using (StreamReader reader = new StreamReader(data))
                {
                    string content = reader.ReadToEnd();
                    string pattern = @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
                    MatchCollection matches = Regex.Matches(content,pattern);
                    List<string> urls = new List<string>();
                    foreach (Match match in matches)
                    {
                            urls.Add(match.Value);
                    }

              }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM