System.Configuration.Configuration 类

方法描述

表示适用于特定计算机、应用程序或资源的配置文件。 此类不能被继承。

语法定义(C# System.Configuration.Configuration 类 的用法)

public sealed class Configuration

构造函数

构造函数名称 构造函数描述

成员/方法

方法名称 方法描述
Equals(Object) 确定指定的 Object 是否等于当前的 Object。 (继承自 Object。)
Finalize 允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。 (继承自 Object。)
GetHashCode 用作特定类型的哈希函数。 (继承自 Object。)
GetSection 返回指定的 ConfigurationSection 对象。
GetSectionGroup 获取指定的 ConfigurationSectionGroup 对象。
GetType 获取当前实例的 Type。 (继承自 Object。)
MemberwiseClone 创建当前 Object 的浅表副本。 (继承自 Object。)
Save() 将包含在此 Configuration 对象中的配置设置写入到当前的 XML 配置文件中。
Save(ConfigurationSaveMode) 将包含在此 Configuration 对象中的配置设置写入到当前的 XML 配置文件中。
Save(ConfigurationSaveMode, Boolean) 将包含在此 Configuration 对象中的配置设置写入到当前的 XML 配置文件中。
SaveAs(String) 将包含在此 Configuration 对象中的配置设置写入到指定的 XML 配置文件中。
SaveAs(String, ConfigurationSaveMode) 将包含在此 Configuration 对象中的配置设置写入到指定的 XML 配置文件中。
SaveAs(String, ConfigurationSaveMode, Boolean) 将包含在此 Configuration 对象中的配置设置写入到指定的 XML 配置文件中。
ToString 返回表示当前对象的字符串。 (继承自 Object。)

提示和注释

配置设置存储在配置文件的层次结构中。 Configuration 类实例表示的所有配置文件的配置设置的合并视图,这些配置设置适用于特定的物理实体(如计算机)或逻辑实体(如应用程序或网站)。 逻辑实体可以存在于本地计算机或远程服务器上。 有关配置文件的信息,请参见 配置文件 和 ASP.NET 配置文件。

如果指定实体没有对应的配置文件,则 Configuration 对象将表示 Machine.config 文件定义的默认配置设置。

可通过使用以下类来获取 Configuration 对象:

ConfigurationManager 类(如果实体是客户端应用程序)。

WebConfigurationManager 类(如果实体是 Web 应用程序)。

返回 Configuration 对象的方法的名称以 "Open" 开头。

还可以生成一个配置文件,用于代表 Configuration 对象中的配置设置。 为此,请使用下列方法之一:

调用 Save 方法来创建新配置文件。

调用 SaveAs 方法以在其他位置生成新的配置文件。

创建配置文件的方法的名称以 "Save" 开头。

注意

若要启用对远程服务器上配置设置的访问,请使用 Aspnet_regiis 命令行工具。 有关此工具的更多信息,请参见 ASP.NET IIS 注册工具 (Aspnet_regiis.exe)。 有关创建和访问自定义配置设置(而不是包括在 .NET Framework 中的内部节)的更多信息,请参考 ConfigurationSection。

对实现者的说明

Configuration 类提供编程访问以编辑配置文件。 可以使用 WebConfigurationManager 类为 Web 应用程序提供的“Open”方法之一,或者使用 ConfigurationManager 类为客户端应用程序提供的“Open”方法之一。 这些方法返回一个 Configuration 对象,该对象又提供处理基础配置文件的方法和属性。 您可以访问这些文件以读写配置信息。

请使用 GetSection 方法或 GetSectionGroup 方法读取配置信息。 请注意,进行读取操作的用户或进程必须具有以下权限:

在当前配置层次结构级别下对配置文件的读取权限。

对所有父级配置文件进行读取的权限。

如果应用程序需要以只读方式访问其自身的配置,则建议您使用 Web 应用程序的 GetSection 方法重载。 对于客户端应用程序,使用 GetSection 方法。

这些方法提供对当前应用程序的缓存配置值的访问;与 Configuration 类相比,这样做可以提供更好的性能。

注意

如果使用静态 GetSection 方法,其采用了路径参数,则该路径参数必须引用正在其中运行该代码的应用程序,否则将忽略该参数并返回当前运行的应用程序的配置信息。

使用 Save 方法之一写入配置信息。 请注意,进行写入操作的用户或进程必须具有以下权限:

对配置层次结构中当前级别的配置文件和目录的写入权限。

对所有配置文件的读取权限。

Topic

Location

如何:使用 SqlDataSource 控件连接到 Oracle 数据库生成 ASP .NET Web 应用程序

System.Configuration.Configuration 类例子

下面的代码示例演示如何使用 Configuration 类访问配置文件元素。

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Specialized;

// Before compiling this application, 
// remember to reference the System.Configuration assembly in your project. 
#region CustomSection class

// Define a custom section. This class is used to
// populate the configuration file.
// It creates the following custom section:
//  .
public sealed class CustomSection : ConfigurationSection
{

    public CustomSection()
    {

    }


    [ConfigurationProperty("name",
     DefaultValue = "Contoso",
     IsRequired = true,
     IsKey = true)]
    public string Name
    {
        get
        {
            return (string)this["name"];
        }
        set
        {
            this["name"] = value;
        }
    }

    [ConfigurationProperty("url",
        DefaultValue = "http://www.contoso.com",
        IsRequired = true)]
    [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
    public string Url
    {
        get
        {
            return (string)this["url"];
        }
        set
        {
            this["url"] = value;
        }
    }

    [ConfigurationProperty("port",
        DefaultValue = (int)8080,
        IsRequired = false)]
    [IntegerValidator(MinValue = 0,
        MaxValue = 8080, ExcludeRange = false)]
    public int Port
    {
        get
        {
            return (int)this["port"];
        }
        set
        {
            this["port"] = value;
        }
    }



}

#endregion

#region Using Configuration Class
class UsingConfigurationClass
{


    // Show how to create an instance of the Configuration class
    // that represents this application configuration file.  
    static void CreateConfigurationFile()
    {
        try
        {

            // Create a custom configuration section.
            CustomSection customSection = new CustomSection();

            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // Create the custom section entry  
            // in  group and the 
            // related target section in .
            if (config.Sections["CustomSection"] == null)
            {
                config.Sections.Add("CustomSection", customSection);
            }

            // Create and add an entry to appSettings section.

            string conStringname="LocalSqlServer";
            string conString = @"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true";
            string providerName="System.Data.SqlClient";

            ConnectionStringSettings connStrSettings = new ConnectionStringSettings();
            connStrSettings.Name = conStringname;
            connStrSettings.ConnectionString= conString;
            connStrSettings.ProviderName = providerName;

            config.ConnectionStrings.ConnectionStrings.Add(connStrSettings);

            // Add an entry to appSettings section.
            int appStgCnt =
                ConfigurationManager.AppSettings.Count;
            string newKey = "NewKey" + appStgCnt.ToString();

            string newValue = DateTime.Now.ToLongDateString() +
              " " + DateTime.Now.ToLongTimeString();

            config.AppSettings.Settings.Add(newKey, newValue);

            // Save the configuration file.
            customSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Full);

            Console.WriteLine("Created configuration file: {0}",
                config.FilePath);

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("CreateConfigurationFile: {0}", err.ToString());
        }

    }

    // Show how to use the GetSection(string) method.
    static void GetCustomSection()
    {
        try
        {

            CustomSection customSection;

            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            customSection =
                config.GetSection("CustomSection") as CustomSection;

            Console.WriteLine("Section name: {0}", customSection.Name);
            Console.WriteLine("Url: {0}", customSection.Url);
            Console.WriteLine("Port: {0}", customSection.Port);

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("Using GetSection(string): {0}", err.ToString());
        }

    }


    // Show how to use different modalities to save 
    // a configuration file.
    static void SaveConfigurationFile()
    {
        try
        {

            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Save the full configuration file and force save even if the file was not modified.
            config.SaveAs("MyConfigFull.config", ConfigurationSaveMode.Full, true);
            Console.WriteLine("Saved config file as MyConfigFull.config using the mode: {0}",
                ConfigurationSaveMode.Full.ToString());

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

            // Save only the part of the configuration file that was modified. 
            config.SaveAs("MyConfigModified.config", ConfigurationSaveMode.Modified, true);
            Console.WriteLine("Saved config file as MyConfigModified.config using the mode: {0}",
                ConfigurationSaveMode.Modified.ToString());

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

            // Save the full configuration file.
            config.SaveAs("MyConfigMinimal.config");
            Console.WriteLine("Saved config file as MyConfigMinimal.config using the mode: {0}",
                ConfigurationSaveMode.Minimal.ToString());

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("SaveConfigurationFile: {0}", err.ToString());
        }

    }


    // Show how use the AppSettings and ConnectionStrings 
    // properties.
    static void GetSections(string section)
    {
        try
        {

            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Get the selected section.
            switch (section)
            {
                case "appSettings":
                    try
                    {
                        AppSettingsSection appSettings =
                            config.AppSettings as AppSettingsSection;
                        Console.WriteLine("Section name: {0}",
                                appSettings.SectionInformation.SectionName);

                        // Get the AppSettings section elements.
                        Console.WriteLine();
                        Console.WriteLine("Using AppSettings property.");
                        Console.WriteLine("Application settings:");
                        // Get the KeyValueConfigurationCollection 
                        // from the configuration.
                        KeyValueConfigurationCollection settings =
                          config.AppSettings.Settings;

                        // Display each KeyValueConfigurationElement.
                        foreach (KeyValueConfigurationElement keyValueElement in settings)
                        {
                            Console.WriteLine("Key: {0}", keyValueElement.Key);
                            Console.WriteLine("Value: {0}", keyValueElement.Value);
                            Console.WriteLine();
                        }
                    }
                    catch (ConfigurationErrorsException e)
                    {
                        Console.WriteLine("Using AppSettings property: {0}",
                            e.ToString());
                    }
                    break;

                case "connectionStrings":
                    ConnectionStringsSection
                        conStrSection =
                        config.ConnectionStrings as ConnectionStringsSection;
                    Console.WriteLine("Section name: {0}",
                        conStrSection.SectionInformation.SectionName);

                    try
                    {
                        if (conStrSection.ConnectionStrings.Count != 0)
                        {
                            Console.WriteLine();
                            Console.WriteLine("Using ConnectionStrings property.");
                            Console.WriteLine("Connection strings:");

                            // Get the collection elements.
                            foreach (ConnectionStringSettings connection in
                              conStrSection.ConnectionStrings)
                            {
                                string name = connection.Name;
                                string provider = connection.ProviderName;
                                string connectionString = connection.ConnectionString;

                                Console.WriteLine("Name:               {0}",
                                  name);
                                Console.WriteLine("Connection string:  {0}",
                                  connectionString);
                                Console.WriteLine("Provider:            {0}",
                                   provider);
                            }
                        }
                    }
                    catch (ConfigurationErrorsException e)
                    {
                        Console.WriteLine("Using ConnectionStrings property: {0}",
                            e.ToString());
                    }
                    break;

                default:
                    Console.WriteLine(
                        "GetSections: Unknown section (0)", section);
                    break;
            }

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("GetSections: (0)", err.ToString());
        }

    }

    // Show how to use the Configuration object properties 
    // to obtain configuration file information.
    static void GetConfigurationInformation()
    {
        try
        {

            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            Console.WriteLine("Reading configuration information:");

            ContextInformation evalContext =
                config.EvaluationContext as ContextInformation;
            Console.WriteLine("Machine level: {0}",
                evalContext.IsMachineLevel.ToString());

            string filePath = config.FilePath;
            Console.WriteLine("File path: {0}", filePath);

            bool hasFile = config.HasFile;
            Console.WriteLine("Has file: {0}", hasFile.ToString());


            ConfigurationSectionGroupCollection
                groups = config.SectionGroups;
            Console.WriteLine("Groups: {0}", groups.Count.ToString());
            foreach (ConfigurationSectionGroup group in groups)
            {
                Console.WriteLine("Group Name: {0}", group.Name);
               // Console.WriteLine("Group Type: {0}", group.Type);
            }


            ConfigurationSectionCollection
                sections = config.Sections;
            Console.WriteLine("Sections: {0}", sections.Count.ToString());

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("GetConfigurationInformation: {0}",err.ToString());
        }

    }

#endregion 

#region Application Main
    //*** User Interaction Class ***//

    // Obtain user's input and provide feedback.
    // This class contains the application Main() function.
    // It calls the ConfigurationManager methods based 
    // on the user's selection.
    class ApplicationMain
    {
        // Display user's menu.
        public static void UserMenu()
        {
            string applicationName =
                Environment.GetCommandLineArgs()[0] + ".exe";
            StringBuilder buffer = new StringBuilder();

            buffer.AppendLine("Application: " + applicationName);
            buffer.AppendLine("Make your selection.");
            buffer.AppendLine("?    -- Display help.");
            buffer.AppendLine("Q,q  -- Exit the application.");

            buffer.Append("1    -- Instantiate the");
            buffer.AppendLine(" Configuration class.");

            buffer.Append("2    -- Use GetSection(string) to read ");
            buffer.AppendLine(" a custom section.");

            buffer.Append("3    -- Use SaveAs methods");
            buffer.AppendLine(" to save the configuration file.");

            buffer.Append("4    -- Use AppSettings property to read");
            buffer.AppendLine(" the appSettings section.");
            buffer.Append("5    -- Use ConnectionStrings property to read");
            buffer.AppendLine(" the connectionStrings section.");

            buffer.Append("6    -- Use Configuration class properties");
            buffer.AppendLine(" to obtain configuration information.");

            Console.Write(buffer.ToString());
        }

        // Obtain user's input and provide
        // feedback.
        static void Main(string[] args)
        {
            // Define user selection string.
            string selection;

            // Get the name of the application.
            string appName =
                Environment.GetCommandLineArgs()[0];


            // Get user selection.
            while (true)
            {

                UserMenu();
                Console.Write("> ");
                selection = Console.ReadLine();
                if (selection != string.Empty)
                    break;
            }

            while (selection.ToLower() != "q")
            {
                // Process user's input.
                switch (selection)
                {
                    case "1":
                        // Show how to create an instance of the Configuration class.
                        CreateConfigurationFile();
                        break;

                    case "2":
                        // Show how to use GetSection(string) method.
                        GetCustomSection();
                        break;

                    case "3":
                        // Show how to use ConnectionStrings.
                        SaveConfigurationFile();
                        break;

                    case "4":
                        // Show how to use the AppSettings property.
                        GetSections("appSettings");
                        break;

                    case "5":
                        // Show how to use the ConnectionStrings property.
                        GetSections("connectionStrings");
                        break;

                    case "6":
                        // Show how to obtain configuration file information.
                        GetConfigurationInformation();
                        break;


                    default:
                        UserMenu();
                        break;
                }
                Console.Write("> ");
                selection = Console.ReadLine();
            }
        }
    }
#endregion

}

继承层次结构

System.Object

System.Configuration.Configuration

命名空间

namespace: System.Configuration

程序集: System.Configuration(在 System.Configuration.dll 中)

线程安全

此类型的任何公共 static(在 Visual Basic 中为 Shared) 成员都是线程安全的。但不保证所有实例成员都是线程安全的。

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。