用.NET 2.0 Enterprise Library库读写App.config文件(2)

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 <configSectionselement 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.

Enterprise Library是一个开源的.NET应用程序,提供了一系列可重用的软件组件和工具,用于简化企业级应用程序的开发。.NET 6可以使用Enterprise Library,只需要将它添加到项目引用中即可使用。 要使用Enterprise Library,您需要进行以下步骤: 1. 下载并安装Enterprise Library。您可以从NuGet或GitHub上下载最新版本的Enterprise Library。 2. 在Visual Studio中打开您的.NET项目,并在“引用”中添加Enterprise Library的程序集。 3. 在代码中引用Enterprise Library的命名空间,并使用其中的类和方法。 例如,您可以使用Enterprise Library中的数据访问组件来连接数据和执行查询。以下是一个示例代码片段: ```csharp using Microsoft.Practices.EnterpriseLibrary.Data; using System.Data.Common; public class DataAccess { private readonly Database db; public DataAccess() { db = DatabaseFactory.CreateDatabase(); } public DbCommand GetCommand(string sql) { return db.GetSqlStringCommand(sql); } public void ExecuteNonQuery(DbCommand cmd) { db.ExecuteNonQuery(cmd); } public object ExecuteScalar(DbCommand cmd) { return db.ExecuteScalar(cmd); } public DbDataReader ExecuteReader(DbCommand cmd) { return db.ExecuteReader(cmd); } } ``` 在上面的示例中,我们使用Enterprise Library的Database组件来创建数据连接,并使用它来执行查询和操作。您也可以使用其他的Enterprise Library组件,例如日志记录、缓存、安全等等。 总之,Enterprise Library是一个非常有用的.NET,可为企业级应用程序开发提供许多便利,您可以在.NET 6项目中使用它来简化开发过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值