Silverlight as a lite version of the . NET Framework , no corresponding support is provided for the configuration file. Can't we use System.Configuration.ConfigurationManager like we did in winForm ? to access App. configuration information in the. So a better way is to write a configuration file management class ConfigurationManager.
First, create a project in the XML file, named App. , remember to put in the project root directory, easy to set the path behind. Set the Build Action to Resourceand write somethingin App. config .
?
<? XMLVersion="1.0"Encoding="utf-8" ?>
?
<configuration>
?
<appSettings>
?
<addkey="name"Value="srzhz"/>
?
<addkey="University"value="Tsinghua University"/>
?
</appSettings>
?
</configuration>
and then you start creating this ConfigurationManager class.
First, right-click on the project ADD Reference , then select System.Xml.Linq . (Cannot introduce namespace System.Xml.Linq if not added )
and then in ConfigurationManager class, write the following code
?
Using System;
Using system.windows;
Using System.Collections.Generic;
Using System.Windows.Resources;
Using System.IO;
Using System.Xml.Linq;
Using System.Reflection;
?
namespace SilverlightApplication92
{
<summary>
?
Access appSettings from a configuration file
?
</summary>
?
<remarks>Your appConfig file must is in the root of Your applcation</remarks>
?
PublicstaticclassConfigurationManager
{
Static ConfigurationManager ()
{
AppSettings = newDictionary<string, string> ();
Readsettings ();
}
?
PublicStaticDictionary<string, string> AppSettings { get; set;}
?
Privatestaticvoid readsettings ()
{
Get the name of the executing assemby-we is going to being 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 (The 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);
}
}
}
}
}
You can then call this class to get the configuration information. For example:
String name = ConfigurationManager. appsettings["name"];
Ways to use configuration files in Silverlight