Tuesday, April 23, 2013

download data from Url in c#

string yahooURL = @"http://download.finance.yahoo.com/d/quotes.csv?s=" + Cmbsym.Text + "&f=sl1d1t1c1hgvbap2" ;
            string GetData = GetDataFromURL(yahooURL);



public static string GetDataFromURL( string URL)
        {
            string Content = "" ;
            int Failure = 0;
            HttpWebRequest WebReq;
            HttpWebResponse WebResp = null ;
            StreamReader Strm = null ;
        TryAgain:
            try
            {
                if (Failure == 3)
                    return "" ;

                WebReq = ( HttpWebRequest)WebRequest .Create(URL);
                WebReq.Timeout = 50000;
                WebResp = ( HttpWebResponse)WebReq.GetResponse();
                Strm = new StreamReader (WebResp.GetResponseStream());
                Content = Strm.ReadToEnd();
                Strm.Close();
                Strm.Dispose();
                WebResp.Close();
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("(404) Not Found" ))
                { }

                if (Strm != null )
                {
                    Strm.Close();
                    Strm.Dispose();
                }

                if (WebResp != null )
                {
                    WebResp.Close();
                }
                Failure++;
                goto TryAgain;
            }

            return Content;
        }

No comments:

Post a Comment