KeyValueConfigurationElement Класс

Определение

Представляет элемент конфигурации, содержащий пару "ключ-значение".

public ref class KeyValueConfigurationElement : System::Configuration::ConfigurationElement
public class KeyValueConfigurationElement : System.Configuration.ConfigurationElement
type KeyValueConfigurationElement = class
    inherit ConfigurationElement
Public Class KeyValueConfigurationElement
Inherits ConfigurationElement
Наследование
KeyValueConfigurationElement

Примеры

В следующем примере кода показано, как использовать члены KeyValueConfigurationElement класса.

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Web;
using System.Web.Configuration;

namespace Samples.Aspnet.Config
{
  class KeyValueConfigCollection
  {
    static void Main(string[] args)
    {
      try
      {
        // Set the path of the config file.
        string configPath = "/aspnet";

        // Get the Web application configuration object.
        Configuration config =
          WebConfigurationManager.OpenWebConfiguration(configPath);

        // Get the section related object.
        AppSettingsSection configSection =
          (AppSettingsSection)config.GetSection
          ("appSettings");

        // Display title and info.
        Console.WriteLine("ASP.NET Configuration Info");
        Console.WriteLine();

        // Display Config details.
        Console.WriteLine("File Path: {0}",
          config.FilePath);
        Console.WriteLine("Section Path: {0}",
          configSection.SectionInformation.Name.ToString());
        Console.WriteLine();

        // Create the KeyValueConfigurationElement.
        KeyValueConfigurationElement myAdminKeyVal = 
          new KeyValueConfigurationElement(
          "myAdminTool", "admin.aspx");

        // Determine if the configuration contains
        // any KeyValueConfigurationElements.
        KeyValueConfigurationCollection configSettings = 
          config.AppSettings.Settings;
        if (configSettings.AllKeys.Length == 0)
        {
          // Add KeyValueConfigurationElement to collection.
          config.AppSettings.Settings.Add(myAdminKeyVal);

          if (!configSection.SectionInformation.IsLocked)
          {
            config.Save();
            Console.WriteLine("** Configuration updated.");
          }
          else
          {
            Console.WriteLine("** Could not update, section is locked.");
          }
        }

        // 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 (Exception e)
      {
        // Unknown error.
        Console.WriteLine(e.ToString());
      }

      // Display and wait
      Console.ReadLine();
    }
  }
}
Imports System.Collections.Generic
Imports System.Text
Imports System.Configuration
Imports System.Web
Imports System.Web.Configuration

Namespace Samples.Aspnet.Config
  Class KeyValueConfigCollection
    Public Shared Sub Main()
      Try
        ' Set the path of the config file.
        Dim configPath As String = "/aspnet"

        ' Get the Web application configuration object.
        Dim config As Configuration = _
          WebConfigurationManager.OpenWebConfiguration(configPath)

        ' Get the section related object.
        Dim configSection As System.Configuration.AppSettingsSection = _
        CType(config.GetSection("appSettings"), System.Configuration.AppSettingsSection)

        '      Dim configSection As AppSettingsSection = _
        '       (AppSettingsSection)config.GetSection("appSettings")

        ' Display title and info.
        Console.WriteLine("ASP.NET Configuration Info")
        Console.WriteLine()

        ' Display Config details.
        Console.WriteLine("File Path: {0}", config.FilePath)
        Console.WriteLine("Section Path: {0}", _
          configSection.SectionInformation.Name.ToString())
        Console.WriteLine()

        ' Create the KeyValueConfigurationElement.
        Dim myAdminKeyVal As KeyValueConfigurationElement = _
          New KeyValueConfigurationElement _
          ("myAdminTool", "admin.aspx")


        ' Determine if the configuration contains
        ' any KeyValueConfigurationElements.
        Dim configSettings As KeyValueConfigurationCollection = _
        config.AppSettings.Settings()

        If configSettings.AllKeys.Length = 0 Then
          ' Add KeyValueConfigurationElement to collection.
          config.AppSettings.Settings.Add(myAdminKeyVal)

          If Not configSection.SectionInformation.IsLocked Then
            config.Save()
            Console.WriteLine("** Configuration updated.")
          Else
            Console.WriteLine("** Could not update, section is locked.")
          End If
        End If

        ' Get the KeyValueConfigurationCollection 
        ' from the configuration.
        Dim settings As KeyValueConfigurationCollection = _
        config.AppSettings.Settings()

        ' Display each KeyValueConfigurationElement.
        Dim keyValueElement As KeyValueConfigurationElement
        For Each keyValueElement In settings
          Console.WriteLine("Key: {0}", keyValueElement.Key)
          Console.WriteLine("Value: {0}", keyValueElement.Value)
          Console.WriteLine()
        Next

      Catch e As System.ArgumentException
        ' Unknown error.
        Console.WriteLine(e.ToString())
      End Try
      ' Display and wait
      Console.ReadLine()
    End Sub
  End Class
End Namespace

Комментарии

Объект KeyValueConfigurationElement наследует от ConfigurationElement базового класса. Объект ConfigurationElement представляет элемент в файле конфигурации. Объект KeyValueConfigurationElement может принадлежать в KeyValueConfigurationCollection коллекции.

Конструкторы

Имя Описание
KeyValueConfigurationElement(String, String)

Инициализирует новый экземпляр KeyValueConfigurationElement класса на основе предоставленных параметров.

Свойства

Имя Описание
CurrentConfiguration

Возвращает ссылку на экземпляр верхнего уровня Configuration , представляющий иерархию конфигурации, к которой принадлежит текущий ConfigurationElement экземпляр.

(Унаследовано от ConfigurationElement)
ElementInformation

ElementInformation Возвращает объект, содержащий не настраиваемую информацию и функциональные возможности ConfigurationElement объекта.

(Унаследовано от ConfigurationElement)
ElementProperty

ConfigurationElementProperty Возвращает объект, представляющий ConfigurationElement сам объект.

(Унаследовано от ConfigurationElement)
EvaluationContext

Возвращает объект ContextInformation для объекта ConfigurationElement.

(Унаследовано от ConfigurationElement)
HasContext

Возвращает значение, указывающее, является CurrentConfigurationли null свойство.

(Унаследовано от ConfigurationElement)
Item[ConfigurationProperty]

Возвращает или задает свойство или атрибут этого элемента конфигурации.

(Унаследовано от ConfigurationElement)
Item[String]

Возвращает или задает свойство, атрибут или дочерний элемент этого элемента конфигурации.

(Унаследовано от ConfigurationElement)
Key

Возвращает ключ KeyValueConfigurationElement объекта.

LockAllAttributesExcept

Возвращает коллекцию заблокированных атрибутов.

(Унаследовано от ConfigurationElement)
LockAllElementsExcept

Возвращает коллекцию заблокированных элементов.

(Унаследовано от ConfigurationElement)
LockAttributes

Возвращает коллекцию заблокированных атрибутов.

(Унаследовано от ConfigurationElement)
LockElements

Возвращает коллекцию заблокированных элементов.

(Унаследовано от ConfigurationElement)
LockItem

Возвращает или задает значение, указывающее, заблокирован ли элемент.

(Унаследовано от ConfigurationElement)
Properties

Возвращает коллекцию свойств.

Value

Возвращает или задает значение KeyValueConfigurationElement объекта.

Методы

Имя Описание
DeserializeElement(XmlReader, Boolean)

Считывает XML из файла конфигурации.

(Унаследовано от ConfigurationElement)
Equals(Object)

Сравнивает текущий ConfigurationElement экземпляр с указанным объектом.

(Унаследовано от ConfigurationElement)
GetHashCode()

Возвращает уникальное значение, представляющее текущий ConfigurationElement экземпляр.

(Унаследовано от ConfigurationElement)
GetTransformedAssemblyString(String)

Возвращает преобразованную версию указанного имени сборки.

(Унаследовано от ConfigurationElement)
GetTransformedTypeString(String)

Возвращает преобразованную версию указанного имени типа.

(Унаследовано от ConfigurationElement)
GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
Init()

Задает объект исходному KeyValueConfigurationElement состоянию.

InitializeDefault()

Используется для инициализации набора значений по умолчанию для ConfigurationElement объекта.

(Унаследовано от ConfigurationElement)
IsModified()

Указывает, был ли изменен этот элемент конфигурации после последнего сохранения или загрузки при реализации в производном классе.

(Унаследовано от ConfigurationElement)
IsReadOnly()

Возвращает значение, указывающее, доступен ли ConfigurationElement объект только для чтения.

(Унаследовано от ConfigurationElement)
ListErrors(IList)

Добавляет ошибки недопустимого свойства в этом ConfigurationElement объекте и во все подэлементы в переданный список.

(Унаследовано от ConfigurationElement)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
OnDeserializeUnrecognizedAttribute(String, String)

Возвращает значение, указывающее, обнаружен ли неизвестный атрибут во время десериализации.

(Унаследовано от ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Возвращает значение, указывающее, обнаружен ли неизвестный элемент во время десериализации.

(Унаследовано от ConfigurationElement)
OnRequiredPropertyNotFound(String)

Создает исключение, если обязательное свойство не найдено.

(Унаследовано от ConfigurationElement)
PostDeserialize()

Вызывается после десериализации.

(Унаследовано от ConfigurationElement)
PreSerialize(XmlWriter)

Вызывается перед сериализацией.

(Унаследовано от ConfigurationElement)
Reset(ConfigurationElement)

Сбрасывает внутреннее состояние ConfigurationElement объекта, включая блокировки и коллекции свойств.

(Унаследовано от ConfigurationElement)
ResetModified()

Сбрасывает значение IsModified() метода false на момент реализации в производном классе.

(Унаследовано от ConfigurationElement)
SerializeElement(XmlWriter, Boolean)

Записывает содержимое этого элемента конфигурации в файл конфигурации при реализации в производном классе.

(Унаследовано от ConfigurationElement)
SerializeToXmlElement(XmlWriter, String)

Записывает внешние теги этого элемента конфигурации в файл конфигурации при реализации в производном классе.

(Унаследовано от ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

Задает свойству указанное значение.

(Унаследовано от ConfigurationElement)
SetReadOnly()

IsReadOnly() Задает свойство для ConfigurationElement объекта и всех вложенных элементов.

(Унаследовано от ConfigurationElement)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

Изменяет объект для удаления всех значений ConfigurationElement , которые не должны быть сохранены.

(Унаследовано от ConfigurationElement)

Применяется к

См. также раздел