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

原文出处:http://geekswithblogs.net/akraus1/articles/64871.aspx

 

       今天我将介绍.NET 2.0System.Configuration命名空间的最大变化。我注意到我的Blog每天都差不多每天都被Google命中20次,他们大部分都是搜索如何配置.NET 2.0 Enterprise Library的,也有一部分是寻找如下问题的答案的:

l         如何读写App.Config文件(我就是这样才看到作者的Blog)的;

l         如何使用System.Configuration机制来存储对象列表;

 

其实还有更多更充分的原因,来让我关注System.Configuraion命名空间,该命名空间自.NET 1.0/1.1以来,主要发生了如下的变化:

l         使用Configuration类来写App.Config文件

l         Windows Forms应用程序引入了新的配置方法

l         App.Config文件中存储更为复杂的对象(集合)

l         It is possible to store Connection Strings in the App.Config file see ConnectionSettings this enables you to store you settings on a SQL Server. The Enterprise Library for Sample SqlConfiguration exercises this by implementing a SqlConfigurationSource which can store and retrieve a ConfigurationSection.

那么,从那里开始好呢?我想还是先解释一下配置文件,然后再说明如何在应用中使用程序来创建配置文件;

 

读写AppSettings的最简单方法

 

如果你只在App.Config文件里面存储Key/Value对,那么你可以使用App.Config的一个保留的Section来存储这些信息;往文件里面添加一个<appsettings>Section,之后在该Section内添加你的Key/Value对,不过要使用<add key=”xxx” value=”xxxx”/>的形式,示例如下:

App.Config

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <appSettings>

    <add key="Setting1" value="Very" />

    <add key="Setting2" value="Easy" />

  </appSettings>

</configuration>

 

.NET2.0 中,访问数据的API也已经发生了变化,旧有的线性访问方法ConfigurationSettings.AppSettings已经不再推荐使用,替代品是ConfigurationManager.AppSettings Beside from the naming change you can now also write your application settings. 针对于“只读”的访问,你可以看看下面定义的ShowConfig函数。另外, “修改上次更改时间”在Main函数中展示:

using System;

using System.Collections.Generic;

using System.Text;

using System.Configuration;

 

namespace AppSettings

{

    class Program

    {

        static void ShowConfig()

        {

            // For read access you do not need to call the OpenExeConfiguraton

            foreach (string key in ConfigurationManager.AppSettings)

            {

                string value = ConfigurationManager.AppSettings[key];

                Console.WriteLine("Key: {0}, Value: {1}", key, value);

            }

        }

 

        static void Main(string[] args)

        {

            ShowConfig();

 

            // Open App.Config of executable

            System.Configuration.Configuration config =

              ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

 

            // Add an Application Setting.

            config.AppSettings.Settings.Add("Modification Date",

              DateTime.Now.ToLongTimeString() + " ");

 

            // Save the configuration file.

            config.Save(ConfigurationSaveMode.Modified);

 

            // Force a reload of a changed section.

            ConfigurationManager.RefreshSection("appSettings");

 

            ShowConfig();

 

        }

    }

}

Expected Output:

Key: Settings1, Value: Very
Key: Setting2, Value: Easy
Key: Settings1, Value: Very
Key: Setting2, Value: Easy
Key: Modification Date, Value: 01:21:03

 

       使用这种方法,可以对的key/value对进行读、写,不过这没有挖掘System.Configuration命名空间的威力。下面示例,我会介绍针对Forms应用程序而引入的配置机制,以及如何使用Enterprise Library helper类来存储对象列表。

 

       Windows Forms Configuration

       When developing Windows Forms with VS2005 you get for free a new configuration mechansim. They Forms designers were so nice to create from your config values automatically an access class and came up with an consistent model to store application global config files in the app.config.exe file and user specific settings within the user profile in user.config.
Please note that the Forms configuration model is not available in class library projects since you have no App.config file for your Dll. When you add a settings file to your class library project you can and merge the settings with the App.config  file of your hosting executable. This can be useful if you want to enforce that every application that uses your library can have its own settings inside the App.config file of the executable. You have the freedom to store your settings where ever you would like to. Any provider can be plugged into your config data access class by decorating your configuration class with the SettingsProviderAttribute. If none is specified the LocalFileSettingsProvider is used which relies on the System.Configuration. This is the reason why you do not need to reference the System.Configuration assembly in a windows forms but you see the System.Configuration assembly loaded in your windows forms application. You can check it with the debugger in the loaded modules list.
Below is a new Windows Forms project shown  which was generated via New->Project->Windows Application. The new configuration features are visible in the Properties folder of your project. There go your resources and the automatically generated strongly typed resource access class with static properties to allow easy and type safe access to your resources. This is similar to the old C programming model with windows resources. You had an header file with resource ids generated by the resource compiler which spits out an header file which is compiled (compile time checking of the existence of resources) and an object file which is linked into you target. Now you have also compile time checking in .NET if you access your resources via the static properties.
The configuration features surface in the auto generated Settings.settings file and Settings.Designer.cs.  To create new configuration values you have full Designer integration within Visual Studio (see picture below). In your code you can read/modify these settings via the generated access class. Inside the visual editor you can choose between two scopes for each of your configuration settings: Application and User. The Application scope defines configuration values which cannot be changed by the user and are the same for all users of this application. User scoped settings on the other hand can be changed/created by, well the users and are stored within their local profile. Addendum: Application scoped settings cannot be altered when you save your settings. Only the user settings are written to disk during a save operation!

 



VS 2005 generated Windows Forms application skeleton.


 

用.NET 2.0 Enterprise Library库读写App.config文件 (1) - 地线 - 别再让虚假消息充斥这本已混乱的世界

 



Settings.settings (Generated by Visual Studio)

 

                <?xml version='1.0' encoding='utf-8'?>

                <SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="WindowsApplication1.Properties" GeneratedClassName="Settings">

                  <Profiles />

                  <Settings>

                    <Setting Name="testSetting" Type="System.String" Scope="User">

                      <Value Profile="(Default)">Form1</Value>

                    </Setting>

                  </Settings>

                </SettingsFile>




Settings.Designer.cs (Generated by Visual Studio using the SettingsSingleFileGenerator as Custom Build Tool)

    namespace WindowsApplication1.Properties 

    {

       internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase 

       {

       

          private static Settings defaultInstance = 

            ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

       

          public static Settings Default 

          {

            get 

            {

                return defaultInstance;

            }

          }

       

          [global::System.Configuration.UserScopedSettingAttribute()]

          [global::System.Configuration.DefaultSettingValueAttribute("Form1")]

          public string testSetting 

          {

             get 

             {

                 return ((string)(this["testSetting"]));

             }

             set 

             {

                 this["testSetting"] = value;

             }

          }

      }

    }


 


To load your settings programtically you only need to to  do a

            Settings set = Settings.Default;

and access your settings via the property of the returned instance.

            string str = set.testSetting;

Wow that was easy. Wasn´t it? Now lets save our changed test setting:

            set.testSetting = "test value";

            set.Save();

That's pretty much it. To display some of your settings in your form you can use data binding and let your users configure the application font, color, .... User specific settings are stored in  %APPDATA%\<AppName>\<AppName><AppConfigName_GUID>\<AssemblyVersion>\user.config. The path to the user config is on my machine is e.g. %APPDATA%\WindowsApplication1\WindowsApplication1.exe_Url_x00ebzylso3e0rtwd1pnxkhduwr34pgb\1.0.0.0. This enables you to install a Windows Forms App as Administrator for all users with some global settings in the executable App.config and user specific settings which are stored in the user profile. If your users are in a domain with a roaming profile they will get the same profile and thus the same user settings on every computer they work.

Is this new mechanism compatible with the old one?

Yes it is. Even more: These nice classes do rely heavily on the System.Configuration features. Each user/application section is put into its own ConfigurationSectionGroupCollection which can be accessed programtically. Every group does contain one or more configuration section/s of the type ClientSettingsSection which does serve as container for your strongly typed key/value pairs. The following code does enumerate all your auto generated settings and does print them out to the Console.



 

            // Get the application configuration file.

            System.Configuration.Configuration config =

                    ConfigurationManager.OpenExeConfiguration(

                    ConfigurationUserLevel.None);

 

            // Get the collection of the section groups.

            ConfigurationSectionGroupCollection sectionGroups = config.SectionGroups;

            // Show the configuration values

            ShowSectionGroupCollectionInfo(sectionGroups);

 

        static void ShowSectionGroupCollectionInfo(ConfigurationSectionGroupCollection sectionGroups)

        {

            ClientSettingsSection clientSection;

            SettingValueElement value;

 

            foreach (ConfigurationSectionGroup group in sectionGroups)  // Loop over all groups

            {

                if (!group.IsDeclared) // Only the ones which are actually defined in app.config

                    continue;

 

                Console.WriteLine("Group {0}", group.Name);

 

                foreach (ConfigurationSection section in group.Sections) // get all sections inside group

                {

                    clientSection = section as ClientSettingsSection;

                    Console.WriteLine("\tSection: {0}", section);

                    if (clientSection == null)

                        continue;

 

                    foreach (SettingElement set in clientSection.Settings)

                    {

                        value = set.Value as SettingValueElement;

 

                        // print out value of each section

                        Console.WriteLine("\t\t{0}: {1}",set.Name,value.ValueXml.InnerText);

                    }

                }

            }

        }



 

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 LibraryDatabase组件来创建数据连接,并使用它来执行查询和操作。您也可以使用其他的Enterprise Library组件,例如日志记录、缓存、安全等等。 总之,Enterprise Library是一个非常有用的.NET,可为企业级应用程序开发提供许多便利,您可以在.NET 6项目中使用它来简化开发过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值