Поделиться через


ConfigurationElement Класс

Определение

Представляет элемент в файле конфигурации.

public ref class ConfigurationElement
public class ConfigurationElement
type ConfigurationElement = class
Public Class ConfigurationElement
Наследование
ConfigurationElement
Производный

Примеры

В следующем примере реализуется несколько методов и свойств ConfigurationElement класса . В этом примере получается ConfigurationSection объект для moduleProvider раздела и возвращается ConfigurationElementCollection из этого раздела. В этом примере выполняется перебор каждой ConfigurationElement из полученных коллекций.

[ModuleServiceMethod(PassThrough = true)]
public ArrayList GetElementCollection()
{
    // Use an ArrayList to transfer objects to the client.
    ArrayList arrayOfConfigPropertyBags = new ArrayList();

    ServerManager serverManager = new ServerManager();
    Configuration administrationConfig = serverManager.GetAdministrationConfiguration();
    ConfigurationSection moduleProvidersSection = 
        administrationConfig.GetSection("moduleProviders");
    ConfigurationElementCollection elementCollection = 
        moduleProvidersSection.GetCollection();
    // If there is a configuration element with the name of TestDemo(Modified), delete it.
    ConfigurationElement elementtoremove = null;
    foreach (ConfigurationElement moduleproviderelement in elementCollection)
    {
        if(moduleproviderelement.Attributes["name"].Value.ToString() == "TestDemo(Modified)")
        {
            elementtoremove = moduleproviderelement;
        }
    }
    if (elementtoremove != null)
    {
        elementCollection.Remove(elementtoremove);
    }
    foreach (ConfigurationElement moduleproviderelement in elementCollection)
    {
        PropertyBag elementBag = new PropertyBag();
        elementBag[ConfigurationDemoGlobals.SchemaName] = 
            moduleproviderelement.Schema.Name;
        elementBag[ConfigurationDemoGlobals.ElementTagName] = 
            moduleproviderelement.ElementTagName;
        ArrayList attributeArrayList = new ArrayList();
        // Loop through all attributes in the element attribute list.
        // Get the attribute name and value.
        foreach (ConfigurationAttribute attribute in moduleproviderelement.Attributes)
        {
            PropertyBag attributeBag = new PropertyBag();
            attributeBag[ConfigurationDemoGlobals.AttributeName] = attribute.Name;
            attributeBag[ConfigurationDemoGlobals.AttributeValue] = attribute.Value;
            // Change the value of the provider name "TestDemo" to "TestDemo(Modified)".
            if (attribute.Value.ToString() == "TestDemo")
            {
                // Use any of the following lines to set the attribute value.
                // attribute.Value = "TestDemo(Modified)";
                moduleproviderelement.SetAttributeValue(
                    "name", "TestDemo(Modified)");
                // moduleproviderelement["name"] = "TestDemo(Modified)";
                // Use any of the following lines to retrieve the attribute value.
                // attributeBag[ConfigurationDemoGlobals.AttributeName] = "name";
                attributeBag[ConfigurationDemoGlobals.AttributeName] =
                    moduleproviderelement.GetAttributeValue("name");
                // attributeBag[ConfigurationDemoGlobals.AttributeName] =
                //    moduleproviderelement["name"];
                // Set the element's lockItem attribute.
                moduleproviderelement.SetMetadata("lockItem", true); // persisted in Administration.config          

            }
            attributeArrayList.Add(attributeBag);
        }
        elementBag[ConfigurationDemoGlobals.AttributeArrayList] = attributeArrayList;
        arrayOfConfigPropertyBags.Add(elementBag);
    }
    // Create a new element. It must have a unique name.
    ConfigurationElement newelement;
    bool newelementexists = false;
    foreach (ConfigurationElement element in elementCollection)
    {
        if (element.Attributes["name"].Value.ToString() == "TestDemo")
        {
            newelementexists = true;
        }
    }
    if (!newelementexists)
    {
        newelement = elementCollection.CreateElement("add");
        newelement.Attributes["name"].Value = "TestDemo";
        newelement.Attributes["Type"].Value = "TestDemo.TestDemoModuleProvider, TestDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=104f78e73dc54601";
        elementCollection.Add(newelement);
    }
    // CommitChanges to persist the changes to Administration.config.
    serverManager.CommitChanges();
    return arrayOfConfigPropertyBags;
}

Комментарии

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

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

ConfigurationElement()

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

Свойства

Attributes

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

ChildElements

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

ElementTagName

Представляет элемент в файле конфигурации.

IsLocallyStored

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

Item[String]

Возвращает или задает атрибут с указанным именем.

Methods

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

RawAttributes

Представляет элемент в файле конфигурации.

Schema

Возвращает схему для текущего элемента.

Методы

Delete()

Представляет элемент в файле конфигурации.

GetAttribute(String)

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

GetAttributeValue(String)

Возвращает значение заданного атрибута.

GetChildElement(String)

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

GetChildElement(String, Type)

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

GetCollection()

Возвращает коллекцию по умолчанию для текущего элемента конфигурации.

GetCollection(String)

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

GetCollection(String, Type)

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

GetCollection(Type)

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

GetMetadata(String)

Возвращает значения метаданных из схемы элемента.

SetAttributeValue(String, Object)

Задает значение указанного атрибута.

SetMetadata(String, Object)

Задает значения метаданных из схемы элемента.

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