Reading configurations from a file in Silverlight is little cumbersome. You can add app.config file to a silverlight application but after compiling the application, a compressed assembly will be created which will have the app.config also. The assembly will have .xap extension which you can change to .zip to see the contents. Now the problem is you can not modify the app.config as and when required... each time you will have to take a new build... :(
In my case I had multiple servers and each server had different values for the config keys so using the app.config was ruled out. I wanted to put my config data in a normal XML file and read it from the silverlight app. But that is not a straight forward job..! After a lot of research i came up with an approach to put an xml file in the ClientBin folder of the web application which hosts the Silverlight tool and read the xml with the help of a WebClient object.
Here is the code for the same:
WebClient configClient = new WebClient();
configClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(LoadConfigurationsHandler);
configClient.DownloadStringAsync(new Uri("customConfig.xml", UriKind.RelativeOrAbsolute));
The file customConfig.xml is put under ClientBin folder of the host application, which has the .xap file also. Because of that we need not provide a URL for the config file.
After reading the xml file, set it to a property on the App.xaml.cs, so that it can be accessed anytime during the lifetime of the application.
void LoadConfigurationsHandler(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
currentApp = (App)App.Current;
currentApp.AppConfig = e.Result;
}
else
{
MessageBox.Show("There was an unanticipated error in retrieving data from the server.", "Error", MessageBoxButton.OK);
}
}
Here the AppConfig is a string property created on the App.xaml.cs
Once this value is set, you can always obtain the config values from the AppConfig property.
currentApp = (App)App.Current;
XElement root = XDocument.Parse(currentApp.AppConfig).Element("testroot");
Hope that should be helpful for reading config files.
There is another approach on CodeProject which is slightly complicated. I felt the above method to be easier.. :)