silverlight 实现 读取app.config 或 web.config

来源:互联网 发布:软件著作权 授权 编辑:程序博客网 时间:2024/05/19 20:39
 

源码地址:稍后更新  

      无意中写一个silverlight程序,准备做成浏览器外运行模式。就想如果是浏览器外运行模式,它就是个实实在在的C/S程序了应该和以前的WinForm应用程序一样,能读取本

地系统文件。然后就开始google之旅,发现一篇误人子弟之文章 《SilverLight C#程序之:读取并修改App.config文件》,纯粹瞎扯淡。用silverlight引用什

System.Configuration云云,写过silverlight程序的人都知道 silverlight只支持 silverlight类库的引用。而这个类库根本不是为silverlight而写的,所以这个方法行不通。

      此方法有很大局限性,使用慎用。其原理从应用程序包里读取资源文件。

     原文章地址http://andrewtokeley.net/archive/2011/01/23/silverlight-4-ndash-simple-configuration-manager.aspx

    主要有几点要点,

APP.config 文件通过添加XML文件改XML后缀名实现。

其内部代码如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="test" value="123456llll"/>
  </appSettings>
</configuration>

APP.CONFIG 必须把生成文件选项 设置为 Resource 模式。否则会读取不到资源文件。

ConfigurationManager静态类模拟了咋们通常使用的System.configuration,需要引用using System.Xml.Linq;

 

ConfigurationManager类如下:

 /// <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);
                }
            }
        }
    }

源码地址:稍后更新  

原创粉丝点击