[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Get weather forecast data in C#

[Get weather forecast data in C#]

There are many sites that offer weather condition and weather forecast services. All of the ones I found required you to have a developer key, although most of them have a free membership that works for a simple program like this one.

This example uses the OpenWeatherMap service. (I don't particularly recommend this site over the others, but it is fairly easy to use.)

Some sites let you access remote functions by using SOAP (Simple Object Access Protocol) or other methods. With OpenWeatherMap you just navigate to a URL and it returns weather data.

For (somewhat poorly written) information about the API, go to http://openweathermap.org/api. The pages linked to that one provide information about the format of the URLs you need to use and the types of data returned.

This example uses two kinds of URL: one to return the current weather conditions and one to return a forecast.

The current condition URL has this format:

http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml &units=imperial&APPID=API_KEY


  • q=London is the location of interest. This can include values such as a place name, a city and country name, or a location code. The returned data includes the location code so if you look up a city once by name, you can save the location code for later searches.
  • mode=xml indicates that I want the returned results in an XML document.
  • APPID=API_KEY is the developer key you get when you sign up.
  • units=imperial tells the server that I want imperial units such as degrees Fahrenheit instead of degrees Celsius or Kelvin.

The weather forecast URL has this format:

http://api.openweathermap.org/data/2.5/forecast?q=London&mode=xml &units=imperial&APPID=API_KEY

The only difference is that the final part before the ? character is forecast instead of weather.

The following code shows how the program gets current conditions and forecasts.

// Enter your API key here. // Get an API key by making a free account at: // http://home.openweathermap.org/users/sign_in private const string API_KEY = "9749874xw2kfiq9029j092m0j9kfj07e"; // Query URLs. Replace @LOC@ with the location. private const string CurrentUrl = "http://api.openweathermap.org/data/2.5/weather?" + "q=@LOC@&mode=xml&units=imperial&APPID=" + API_KEY; private const string ForecastUrl = "http://api.openweathermap.org/data/2.5/forecast?" + "q=@LOC@&mode=xml&units=imperial&APPID=" + API_KEY; // Get current conditions. private void btnConditions_Click(object sender, EventArgs e) { // Compose the query URL. string url = CurrentUrl.Replace("@LOC@", txtLocation.Text); txtXml.Text = GetFormattedXml(url); } // Get a forecast. private void btnForecast_Click(object sender, EventArgs e) { // Compose the query URL. string url = ForecastUrl.Replace("@LOC@", txtLocation.Text); txtXml.Text = GetFormattedXml(url); }

The API_KEY string holds your developer API key. The one shown here is just a random value and not a valid key. Register at http://home.openweathermap.org/users/sign_in to get your own key.

The strings CurrentUrl and ForecastUrl are the URLs to get current conditions and a weather forecast.

The Conditions button's Click event handler replaces the string @LOC@ in the conditions URL string with the location entered in the program's text box. It then calls the GetFormattedXml method to get the returned XML data and it displays it in the txtXml text box.

The Forecast button's Click event handler works similarly except it uses the weather forecast URL.

The following code shows the GetFormattedXml method.

// Return the XML result of the URL. private string GetFormattedXml(string url) { // Create a web client. using (WebClient client = new WebClient()) { // Get the response string from the URL. string xml = client.DownloadString(url); // Load the response into an XML document. XmlDocument xml_document = new XmlDocument(); xml_document.LoadXml(xml); // Format the XML. using (StringWriter string_writer = new StringWriter()) { XmlTextWriter xml_text_writer = new XmlTextWriter(string_writer); xml_text_writer.Formatting = Formatting.Indented; xml_document.WriteTo(xml_text_writer); // Return the result. return string_writer.ToString(); } } }

This method creates a WebClient and calls its DownloadString method to visit the desired URL and fetch the result as a string. The string is XML data holding the result of the query defined by the URL.

Initially the XML data is unformatted so it's hard to read, so the method formats it. To do that, it creates an XmlDocument and loads it with the XML data string. It then creates a StringWriter, makes an XmlTextWriter associated with the StringWriter, and makes the XmlDocument write itself into the XmlTextWriter. That makes the XmlTextWriter feeds its data into the StringWriter. The method then returns the StringWriter object's contents.

Look at the http://openweathermap.org/api pages to see what kinds of information is in the returned XML data, or you can just run the example program and look at the results. Much of the data is pretty easy to understand. For example, the temperature value gives you a temperature.

In my next posts I'll explain some ways you can make the data easier to read.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.