ConfigurationErrorsException Classe

Définition

Exception levée lorsqu’une erreur de configuration s’est produite.

public ref class ConfigurationErrorsException : System::Configuration::ConfigurationException
[System.Serializable]
public class ConfigurationErrorsException : System.Configuration.ConfigurationException
[<System.Serializable>]
type ConfigurationErrorsException = class
    inherit ConfigurationException
Public Class ConfigurationErrorsException
Inherits ConfigurationException
Héritage
Attributs

Exemples

L’exemple de code suivant crée une section personnalisée et génère une ConfigurationErrorsException exception lorsqu’elle modifie ses propriétés.

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

L’exemple suivant est un extrait de configuration utilisé par l’exemple précédent.

<?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>

Remarques

L’exception ConfigurationErrorsException est levée lorsqu’une erreur se produit lors de la lecture ou de l’écriture des informations de configuration.

Constructeurs

Nom Description
ConfigurationErrorsException()

Initialise une nouvelle instance de la classe ConfigurationErrorsException.

ConfigurationErrorsException(SerializationInfo, StreamingContext)

Initialise une nouvelle instance de la classe ConfigurationErrorsException.

ConfigurationErrorsException(String, Exception, String, Int32)

Initialise une nouvelle instance de la classe ConfigurationErrorsException.

ConfigurationErrorsException(String, Exception, XmlNode)

Initialise une nouvelle instance de la classe ConfigurationErrorsException.

ConfigurationErrorsException(String, Exception, XmlReader)

Initialise une nouvelle instance de la classe ConfigurationErrorsException.

ConfigurationErrorsException(String, Exception)

Initialise une nouvelle instance de la classe ConfigurationErrorsException.

ConfigurationErrorsException(String, String, Int32)

Initialise une nouvelle instance de la classe ConfigurationErrorsException.

ConfigurationErrorsException(String, XmlNode)

Initialise une nouvelle instance de la classe ConfigurationErrorsException.

ConfigurationErrorsException(String, XmlReader)

Initialise une nouvelle instance de la classe ConfigurationErrorsException.

ConfigurationErrorsException(String)

Initialise une nouvelle instance de la classe ConfigurationErrorsException.

Propriétés

Nom Description
BareMessage

Obtient une description de la raison pour laquelle cette exception de configuration a été levée.

Data

Obtient une collection de paires clé/valeur qui fournissent des informations supplémentaires définies par l’utilisateur sur l’exception.

(Hérité de Exception)
Errors

Obtient une collection d’erreurs qui détaillent les raisons pour lesquelles cette ConfigurationErrorsException exception a été levée.

Filename

Obtient le chemin d’accès au fichier de configuration qui a provoqué la levée de cette exception de configuration.

HelpLink

Obtient ou définit un lien vers le fichier d’aide associé à cette exception.

(Hérité de Exception)
HResult

Obtient ou définit HRESULT, valeur numérique codée affectée à une exception spécifique.

(Hérité de Exception)
InnerException

Obtient l’instance Exception qui a provoqué l’exception actuelle.

(Hérité de Exception)
Line

Obtient le numéro de ligne dans le fichier de configuration auquel cette exception de configuration a été levée.

Message

Obtient une description étendue de la raison pour laquelle cette exception de configuration a été levée.

Source

Obtient ou définit le nom de l’application ou de l’objet qui provoque l’erreur.

(Hérité de Exception)
StackTrace

Obtient une représentation sous forme de chaîne des images immédiates sur la pile des appels.

(Hérité de Exception)
TargetSite

Obtient la méthode qui lève l’exception actuelle.

(Hérité de Exception)

Méthodes

Nom Description
Equals(Object)

Détermine si l’objet spécifié est égal à l’objet actuel.

(Hérité de Object)
GetBaseException()

En cas de substitution dans une classe dérivée, retourne la Exception qui est la cause racine d’une ou plusieurs exceptions ultérieures.

(Hérité de Exception)
GetFilename(XmlNode)

Obtient le chemin d’accès au fichier de configuration à partir duquel l’objet interne XmlNode a été chargé lorsque cette exception de configuration a été levée.

GetFilename(XmlReader)

Obtient le chemin d’accès au fichier de configuration que l’interne XmlReader a lu lorsque cette exception de configuration a été levée.

GetHashCode()

Sert de fonction de hachage par défaut.

(Hérité de Object)
GetLineNumber(XmlNode)

Obtient le numéro de ligne dans le fichier de configuration représenté par l’objet interne XmlNode lorsque cette exception de configuration a été levée.

GetLineNumber(XmlReader)

Obtient le numéro de ligne dans le fichier de configuration que l’objet interne XmlReader a traité lorsque cette exception de configuration a été levée.

GetObjectData(SerializationInfo, StreamingContext)

Définit l’objet avec le SerializationInfo nom de fichier et le numéro de ligne auquel cette exception de configuration s’est produite.

GetType()

Obtient le type d’exécution de l’instance actuelle.

(Hérité de Exception)
MemberwiseClone()

Crée une copie superficielle du Objectactuel.

(Hérité de Object)
ToString()

Crée et retourne une représentation sous forme de chaîne de l’exception actuelle.

(Hérité de Exception)

Événements

Nom Description
SerializeObjectState

Se produit lorsqu’une exception est sérialisée pour créer un objet d’état d’exception qui contient des données sérialisées sur l’exception.

(Hérité de Exception)

S’applique à