Unlike the full framework, Silverlight 4 doesn’t have built in support to read from an application configuration file – theSystem.Configuration.ConfigurationManager isn’t part of the framework. Of course, Silverlight is a bit different to other applications where users may need to gain access to an app.config file but nevertheless it’s sometimes nice to store and retrieve configuration data in a familiar way.

So here’s a quick and easy way to do it.

Add an XML file to the root of your Silverlight project, rename it to app.config and set it’s build action to Resource.

image

Whack in some appSettings in the same way you would a normal configuration file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="serviceUrl" value="http://myservice.com"/>
    <add key="guestAccountEmail" value="guest@mycompany.com"/>
  </appSettings>
</configuration>

 

Now create your very own ConfigurationManager class (note, you’ll need to add have a reference to System.Xml.Linq).

using System;
using System.Windows;
using System.Collections.Generic;
using System.Windows.Resources;
using System.IO;
using System.Xml.Linq;
using System.Reflection;
 
namespace GoogleReader.API.Tests
{
    /// <summary>
    /// Access appSettings from a configuration file
    /// </summary>
    /// <remarks>Your appConfig file must be in the root of your applcation</remarks>
    public static class ConfigurationManager
    {
 
        static ConfigurationManager()
        {
            AppSettings = new Dictionary<string, string>();
            ReadSettings();
        }
 
        public static Dictionary<string, string> AppSettings { get; set; }
 
        private static void ReadSettings()
        {
            
            // Get the name of the executing assemby - we are going to be looking in the root folder for
            // a file called app.config
            string assemblyName = Assembly.GetExecutingAssembly().FullName;
            assemblyName  = assemblyName.Substring(0, assemblyName .IndexOf(','));
            string url = String.Format("{0};component/app.config", assemblyName);
 
            StreamResourceInfo configFile = Application.GetResourceStream(new Uri(url, UriKind.Relative));
 
            if (configFile != null && configFile.Stream != null)
            {
                Stream stream = configFile.Stream;
                XDocument document = XDocument.Load(stream);
 
                foreach (XElement element in document.Descendants("appSettings").DescendantNodes())
                {
                    AppSettings.Add(element.Attribute("key").Value, element.Attribute("value").Value);
                }
            }
        }
    }
}
 

 

And write the code you’re used to.

 
// Give me a url please
string serviceUrl = ConfigurationManager.AppSettings["serviceUrl"];
 

 

Easy.