ConfigurationErrorsException Класс

Определение

Исключение, которое возникает при возникновении ошибки конфигурации.

public ref class ConfigurationErrorsException : System::Configuration::ConfigurationException
[System.Serializable]
public class ConfigurationErrorsException : System.Configuration.ConfigurationException
public class ConfigurationErrorsException : System.Configuration.ConfigurationException
[<System.Serializable>]
type ConfigurationErrorsException = class
    inherit ConfigurationException
type ConfigurationErrorsException = class
    inherit ConfigurationException
Public Class ConfigurationErrorsException
Inherits ConfigurationException
Наследование
Атрибуты

Примеры

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

using System;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections;

namespace Samples.AspNet
{

    // Define a custom section.
    public sealed class CustomSection :
       ConfigurationSection
    {
        public CustomSection()
        {
        }

        [ConfigurationProperty("fileName", DefaultValue = "default.txt",
                    IsRequired = true, IsKey = false)]
        [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
            MinLength = 1, MaxLength = 60)]
        public string FileName
        {
            get
            {
                return (string)this["fileName"];
            }
            set
            {
                this["fileName"] = value;
            }
        }

        [ConfigurationProperty("maxUsers", DefaultValue = (long)10,
            IsRequired = false)]
        [LongValidator(MinValue = 1, MaxValue = 100,
            ExcludeRange = false)]
        public long MaxUsers
        {
            get
            {
                return (long)this["maxUsers"];
            }
            set
            {
                this["maxUsers"] = value;
            }
        }
    }

    // Create the custom section and write it to
    // the configuration file.
    class UsingConfigurationErrorsException
    {
        // Create a custom section.
        static UsingConfigurationErrorsException()
        {
            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // If the section does not exist in the configuration
            // file, create it and save it to the file.
            if (config.Sections["CustomSection"] == null)
            {
                CustomSection custSection = new CustomSection();
                config.Sections.Add("CustomSection", custSection);
                custSection =
                    config.GetSection("CustomSection") as CustomSection;
                custSection.SectionInformation.ForceSave = true;
                config.Save(ConfigurationSaveMode.Full);
            }
        }
        
        // Modify a custom section and cause configuration 
        // error exceptions.
        static void ModifyCustomSection()
        {

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

                CustomSection custSection =
                   config.Sections["CustomSection"] as CustomSection;

                // Change the section properties.
                custSection.FileName = "newName.txt";
                
                // Cause an exception.
                custSection.MaxUsers = custSection.MaxUsers + 100;

                if (!custSection.ElementInformation.IsLocked)
                    config.Save();
                else
                    Console.WriteLine(
                        "Section was locked, could not update.");
            }
            catch (ConfigurationErrorsException err)
            {

                string msg = err.Message;
                Console.WriteLine("Message: {0}", msg);

                string fileName = err.Filename;
                Console.WriteLine("Filename: {0}", fileName);

                int lineNumber = err.Line;
                Console.WriteLine("Line: {0}", lineNumber.ToString());

                string bmsg = err.BareMessage;
                Console.WriteLine("BareMessage: {0}", bmsg);

                string source = err.Source;
                Console.WriteLine("Source: {0}", source);

                string st = err.StackTrace;
                Console.WriteLine("StackTrace: {0}", st);
            }
        }

        static void Main(string[] args)
        {
            ModifyCustomSection();
        }
    }
}
Imports System.Configuration
Imports System.Collections.Specialized
Imports System.Collections



' Define a custom section.

NotInheritable Public Class CustomSection
    Inherits ConfigurationSection
    
    Public Sub New() 
    
    End Sub
    
    
    <ConfigurationProperty("fileName", DefaultValue:="default.txt", IsRequired:=True, IsKey:=False), StringValidator(InvalidCharacters:=" ~!@#$%^&*()[]{}/;'""|\", MinLength:=1, MaxLength:=60)> _
    Public Property FileName() As String
        Get
            Return CStr(Me("fileName"))
        End Get
        Set(ByVal value As String)
            Me("fileName") = value
        End Set
    End Property
    
    
    <ConfigurationProperty("maxUsers", DefaultValue:=10, IsRequired:=False), LongValidator(MinValue:=1, MaxValue:=100, ExcludeRange:=False)> _
    Public Property MaxUsers() As Long
        Get
            Return Fix(Me("maxUsers"))
        End Get
        Set(ByVal value As Long)
            Me("maxUsers") = value
        End Set
    End Property
End Class


' Create the custom section and write it to
' the configuration file.

Class UsingConfigurationErrorsException
    
    ' Create a custom section.
    Shared Sub New()

        ' Get the application configuration file.
        Dim config _
        As System.Configuration.Configuration = _
        ConfigurationManager.OpenExeConfiguration( _
        ConfigurationUserLevel.None)

        ' If the section does not exist in the configuration
        ' file, create it and save it to the file.
        If config.Sections("CustomSection") Is Nothing Then
            Dim custSection As New CustomSection()
            config.Sections.Add("CustomSection", custSection)
            custSection = config.GetSection("CustomSection")
            custSection.SectionInformation.ForceSave = True
            config.Save(ConfigurationSaveMode.Full)
        End If

    End Sub
    
    
    ' Modify a custom section and cause configuration 
    ' error exceptions.
    Shared Sub ModifyCustomSection() 
        
        Try
            ' Get the application configuration file.
            Dim config _
            As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)

            Dim custSection _
            As CustomSection = _
            config.Sections("CustomSection")
             
            ' Change the section properties.
            custSection.FileName = "newName.txt"
            
            ' Cause an exception.
            custSection.MaxUsers = _
            custSection.MaxUsers + 100
            
            If Not custSection.ElementInformation.IsLocked Then
                config.Save()
            Else
                Console.WriteLine( _
                "Section was locked, could not update.")
            End If
        Catch err As ConfigurationErrorsException
            
            Dim msg As String = err.Message
            Console.WriteLine("Message: {0}", msg)
            Dim fileName As String = err.Filename
            Console.WriteLine("Filename: {0}", _
            fileName)
            Dim lineNumber As Integer = err.Line
            Console.WriteLine("Line: {0}", _
            lineNumber.ToString())
            Dim bmsg As String = err.BareMessage
            Console.WriteLine("BareMessage: {0}", bmsg)
            Dim src As String = err.Source
            Console.WriteLine("Source: {0}", src)
            Dim st As String = err.StackTrace
            Console.WriteLine("StackTrace: {0}", st)
        End Try

    End Sub

    Shared Sub Main(ByVal args() As String) 
        ModifyCustomSection()
    
    End Sub
End Class

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

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="CustomSection" type="Samples.AspNet.CustomSection,
      ConfigurationErrorsException, Version=1.0.0.0, Culture=neutral,
      PublicKeyToken=null" allowDefinition="Everywhere"
      allowExeDefinition="MachineToApplication"
      restartOnExternalChanges="true" />
  </configSections>
  <CustomSection fileName="default.txt" maxUsers="10" />
</configuration>

Комментарии

Исключение ConfigurationErrorsException возникает при возникновении ошибки во время чтения или записи сведений о конфигурации.

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

Имя Описание
ConfigurationErrorsException()

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

ConfigurationErrorsException(SerializationInfo, StreamingContext)
Устаревшие.

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

ConfigurationErrorsException(String, Exception, String, Int32)

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

ConfigurationErrorsException(String, Exception, XmlNode)

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

ConfigurationErrorsException(String, Exception, XmlReader)

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

ConfigurationErrorsException(String, Exception)

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

ConfigurationErrorsException(String, String, Int32)

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

ConfigurationErrorsException(String, XmlNode)

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

ConfigurationErrorsException(String, XmlReader)

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

ConfigurationErrorsException(String)

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

Свойства

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

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

BareMessage

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

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

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

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

Возвращает коллекцию ошибок, которые подробно описывают причины возникновения этого ConfigurationErrorsException исключения.

Filename

Возвращает путь к файлу конфигурации, вызвавшего исключение конфигурации.

HelpLink

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

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

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

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

Exception Возвращает экземпляр, вызвавшего текущее исключение.

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

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

Message

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

Source

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

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

Возвращает строковое представление непосредственных кадров в стеке вызовов.

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

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

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

Методы

Имя Описание
Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

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

При переопределении в производном классе возвращает Exception первопричину одного или нескольких последующих исключений.

(Унаследовано от Exception)
GetFilename(XmlNode)

Возвращает путь к файлу конфигурации, из которого был загружен внутренний XmlNode объект при возникновении этого исключения конфигурации.

GetFilename(XmlReader)

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

GetHashCode()

Служит хэш-функцией по умолчанию.

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

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

GetLineNumber(XmlReader)

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

GetObjectData(SerializationInfo, StreamingContext)
Устаревшие.

SerializationInfo Задает объект с именем файла и номером строки, в котором произошло исключение конфигурации.

GetType()

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

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

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

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

Создает и возвращает строковое представление текущего исключения.

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

События

Имя Описание
SerializeObjectState
Устаревшие.

Происходит при сериализации исключения для создания объекта состояния исключения, содержащего сериализованные данные об исключении.

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

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