用.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);

                    }

                }

            }

        }


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章