Introduction
This article is intended to show you how you can use the Internet to gather and display dynamic content.
Background
While teaching myself C#, I wanted to figure out how to use the HttpWebRequest
and HttpWebResponse
objects to gather information from the Internet. Being new to C#, I decided to rewrite one of my previous C++ applications in C#. What better way to learn the caveats of a new language than to rebuild an existing application in a newer language?
I’d like to thank Mike Gold from C# corner for his articles, Carlos Perez for his progress bar demo, Dion Heskett for his gradient label and Nishant S for his notify icon example. I’m an avid Code Project reader and appreciate all the hard work others have done.
The Code
string sfullpath =
@"http://asp.usatoday.com/weather/" +
@"cityforecast.aspx?LocationID=USVA0023&ps=L1";
HttpWebRequest MyWebReq;
HttpWebResponse MyWebRes;
StreamReader MySReader;
sForecast = "";
sTemp = "";
string sTempPrompt = @"font-size:20px";
MyWebReq = (HttpWebRequest) WebRequest.Create(sfullpath);
MyWebRes = (HttpWebResponse) MyWebReq.GetResponse();
MySReader = new
StreamReader(MyWebRes.GetResponseStream(), Encoding.ASCII);
while( sTemp.IndexOf( sTempPrompt ) == -1 )
{
sTemp = MySReader.ReadLine();
}
MySReader .Close();
sTemp = sTemp.ToLower();
sTemp = sTemp.Trim();
sForecastOriginal = sTemp;
int iTempIndex = sTemp.IndexOf( sTempPrompt );
iTempIndex = iTempIndex + 16;
sForecastOriginal = sForecastOriginal.Substring( iTempIndex, 600 );
sForecast = sForecastOriginal;
sTemp = sTemp.Substring( iTempIndex, 5 );
sTemp = sTemp.Substring( 0, sTemp.IndexOf( "<" ) );
sTemp = sTemp.Trim();
Using the code
The one main point I’d like to make is that since I’m parsing HTML, I’m at the mercy of the website where I’m getting the HTML from. If they decide to dramatically change the setup of their page, then this application might not get the correct data. If a message box pops up, shut the program down and then open it back up again. When the message box shows up, that means the HTML I'm trying to parse is being written.
History
Initial release 1.0.1