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

posted @ 2015-03-19 15:32  xingrun  阅读(652)  评论(0编辑  收藏  举报