Winform 读取 指定\另一个\其他\任意 配置文件

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = @"F:\App1.config"; ;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            string connstr = config.ConnectionStrings.ConnectionStrings["connStr"].ConnectionString;
            MessageBox.Show(connstr);
            string key = config.AppSettings.Settings["key"].Value;
            MessageBox.Show(key);

 

 

 

How To Read/Write Another App.Config File
To open another App.Config file you need to create an instance of ExeConfigurationFileMap. The purpose of this class is not that obvious but we can use it to open another file. Once you have learned this little trick the rest is easy. Here is a little example that does open an file by specifying it's name.

            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

            fileMap.ExeConfigFilename = @"ConfigTest.exe.config";  // relative path names possible

            // Open another config file

            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

 

            // read/write from it as usual

            ConfigurationSection mySection = config.GetSection("mySection");

            config.SectionGroups.Clear(); // make changes to it

            config.Save(ConfigurationSaveMode.Full);  // Save changes


The Microsoft Enterprise Library way has a shorthand utility class for this. It is the FileConfigurationSource which does hide those strange things. Tom Hollander has a nice post explaining this already so I will not repeat the same at my blog.

Another Way to read/write configuration values

A more advanced way to store our settings is to create our own ConfigurationSection. This makes our configuration values distinguishable from other configuration values inside the App.config file. It is a little more complicated since you have to write your own class which content is de/serialized to the App.config file. I am going to show you at first the config file and explain then what code you need to write to read/save these settings to your application configuration file.

App.Config  (Taken from the Enterprise Library Configuration Migration QuickStart Sample)

<configuration>

  <configSections>

    <section name="EditorSettings" type="ConfigurationMigrationQuickStart.EditorFontData, ConfigurationMigrationQuickStart, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null" />

  </configSections>

  <EditorSettings name="Verdana" size="24" style="2" />

</configuration>

 

Most App.config files which contain config data have a <configSections> element where many <section> are defined. The name attribute of an section (in this example "EditorSettings") tells the config system that the class ConfigurationMigrationQuickStart.EditorFontData is responsible for the ser/deserialization of the node <EditorSettings>. The EditorFontData class derives from the ConfigurationSection class and uses the ConfigurationProperty attribute to create a mapping between the properties to de/serialize and the attribute names in names in the App.Config file.

      using System.Text;

      using System.Configuration; 

 

      public class EditorFontData : ConfigurationSection

      {          

 

            public EditorFontData()

            {         

            }

 

            [ConfigurationProperty("name")]

            public string Name

            {

                  get { return (string)this["name"]; }

                  set{ this["name"] = value; }

            }

 

            [ConfigurationProperty("size")]

            public float Size

            {

                  get{ return (float)this["size"]; }

                  set{ this["size"] = value; }

            }

 

            [ConfigurationProperty("style")]

            public int Style

            {

                  get { return (int)this["style"]; }

                  set{ this["style"] = value; }

            }

      }

 

To access an EditorFontData instance with values from your config file you only need to call

   EditorFontData configData = ConfigurationManager.GetSection("EditorSettings") as EditorFontData;

 

Please note that the System.Configuration.ConfigurationManager returns only objects with read only properties. Subsequent calls to GetSection use the cached instance inside the ConfigurationManager. This constraint requires you to create every time a new instance of you e.g. EditorFontData object if you want to write to the App.config file. You even cannot add an object with the same name twice to the System.Configuration.Configuration object. Now comes the fun part: To edit an existing App.config file you have to remove your config object and then add a new object instance to the Configuration object. Only then the Save will succeed.

                EditorFontData configData = new EditorFontData();

                configData.Name = "Arial";

                configData.Size = 20;

                configData.Style = 2;

               

                // Write the new configuration data to the XML file

                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                config.Sections.Remove("EditorSettings");

                config.Sections.Add("EditorSettings", configData);

                config.Save();


To get your hands on the System.Configuration.Configuration object you have to open your App.Config file. The .NET config mechanism supports setting inheritance from the Machine.config from which all settings are inherited. Next comes the App.Config file which is selected by the ConfigurationUserLevel.None file.

http://geekswithblogs.net/akraus1/articles/64871.aspx

转载于:https://www.cnblogs.com/xingrun/p/4350571.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值