开发者

Reading value from remote website using WebClient

开发者 https://www.devze.com 2023-02-15 07:23 出处:网络
{ WebClient client = new WebClient(); // Add a user agent header in case the // requested URI contains a query.
{
    WebClient client = new WebClient();

    // Add a user agent header in case the 
    // requested URI contains a query.

    client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 开发者_运维百科6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

    Stream data = client.OpenRead("http://www.nseindia.com/marketinfo/indices/indexwatch.jsp");
    StreamReader reader = new StreamReader(data);
    string s = null;
    int count = 0;
    while (reader.Read()>0)
    {
        s = reader.ReadLine();
        if (s.Contains("<td class=t1>"))
        {
           s= s.Remove(0, 18);
           s = s.Remove(s.Length - 5);
           count++;
           if (count == 5)
               break;
        }

    }


   // MessageBox.Show(s);
    data.Close();
    reader.Close();
    return s;
}

Will you plz help me to run this ....


You're calling reader.Read() which consumes a character and then you're reading a line. I suggest you change your loop to:

string line;

while ((line = reader.ReadLine()) != null)
{
    ...
}

You should also use using statements so that everything will be closed even if an exception is thrown. Oh, and I'd use string.Substring instead of string.Remove.

I'd probably also use client.DownloadString to get the whole lot in one go instead of opening a stream. It's just simpler.

0

精彩评论

暂无评论...
验证码 换一张
取 消