ConfigurationErrorsException Klass

Definition

Undantaget som utlöses när ett konfigurationsfel har inträffat.

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
Arv
Attribut

Exempel

I följande kodexempel skapas ett anpassat avsnitt och ett ConfigurationErrorsException undantag genereras när dess egenskaper ändras.

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

Följande exempel är ett konfigurationsutdrag som används i föregående exempel.

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

Kommentarer

Undantaget ConfigurationErrorsException utlöses när ett fel inträffar när konfigurationsinformation läses eller skrivs.

Konstruktorer

Name Description
ConfigurationErrorsException()

Initierar en ny instans av ConfigurationErrorsException klassen.

ConfigurationErrorsException(SerializationInfo, StreamingContext)

Initierar en ny instans av ConfigurationErrorsException klassen.

ConfigurationErrorsException(String, Exception, String, Int32)

Initierar en ny instans av ConfigurationErrorsException klassen.

ConfigurationErrorsException(String, Exception, XmlNode)

Initierar en ny instans av ConfigurationErrorsException klassen.

ConfigurationErrorsException(String, Exception, XmlReader)

Initierar en ny instans av ConfigurationErrorsException klassen.

ConfigurationErrorsException(String, Exception)

Initierar en ny instans av ConfigurationErrorsException klassen.

ConfigurationErrorsException(String, String, Int32)

Initierar en ny instans av ConfigurationErrorsException klassen.

ConfigurationErrorsException(String, XmlNode)

Initierar en ny instans av ConfigurationErrorsException klassen.

ConfigurationErrorsException(String, XmlReader)

Initierar en ny instans av ConfigurationErrorsException klassen.

ConfigurationErrorsException(String)

Initierar en ny instans av ConfigurationErrorsException klassen.

Egenskaper

Name Description
BareMessage

Hämtar en beskrivning av varför det här konfigurationsfelet utlöstes.

Data

Hämtar en samling nyckel/värde-par som ger ytterligare användardefinierad information om undantaget.

(Ärvd från Exception)
Errors

Hämtar en samling fel som beskriver orsakerna till att undantaget ConfigurationErrorsException utlöstes.

Filename

Hämtar sökvägen till konfigurationsfilen som orsakade att det här konfigurationsfelet utlöstes.

HelpLink

Hämtar eller anger en länk till hjälpfilen som är associerad med det här undantaget.

(Ärvd från Exception)
HResult

Hämtar eller anger HRESULT, ett kodat numeriskt värde som har tilldelats ett specifikt undantag.

(Ärvd från Exception)
InnerException

Hämtar den Exception instans som orsakade det aktuella undantaget.

(Ärvd från Exception)
Line

Hämtar radnumret i konfigurationsfilen där det här konfigurationsfelet utlöstes.

Message

Hämtar en utökad beskrivning av varför det här konfigurationsfelet utlöstes.

Source

Hämtar eller anger namnet på programmet eller objektet som orsakar felet.

(Ärvd från Exception)
StackTrace

Hämtar en strängrepresentation av de omedelbara ramarna i anropsstacken.

(Ärvd från Exception)
TargetSite

Hämtar den metod som utlöser det aktuella undantaget.

(Ärvd från Exception)

Metoder

Name Description
Equals(Object)

Avgör om det angivna objektet är lika med det aktuella objektet.

(Ärvd från Object)
GetBaseException()

När den åsidosätts i en härledd klass returnerar den Exception som är rotorsaken till ett eller flera efterföljande undantag.

(Ärvd från Exception)
GetFilename(XmlNode)

Hämtar sökvägen till konfigurationsfilen som det interna XmlNode objektet lästes in från när det här konfigurationsfelet utlöstes.

GetFilename(XmlReader)

Hämtar sökvägen till konfigurationsfilen som den interna XmlReader läste när det här konfigurationsfelet utlöstes.

GetHashCode()

Fungerar som standard-hash-funktion.

(Ärvd från Object)
GetLineNumber(XmlNode)

Hämtar radnumret i konfigurationsfilen som det interna XmlNode objektet representerade när det här konfigurationsfelet utlöstes.

GetLineNumber(XmlReader)

Hämtar radnumret i konfigurationsfilen som det interna XmlReader objektet bearbetades när det här konfigurationsfelet utlöstes.

GetObjectData(SerializationInfo, StreamingContext)

Anger objektet SerializationInfo med filnamnet och radnumret där det här konfigurationsfelet inträffade.

GetType()

Hämtar körningstypen för den aktuella instansen.

(Ärvd från Exception)
MemberwiseClone()

Skapar en ytlig kopia av den aktuella Object.

(Ärvd från Object)
ToString()

Skapar och returnerar en strängrepresentation av det aktuella undantaget.

(Ärvd från Exception)

Händelser

Name Description
SerializeObjectState

Inträffar när ett undantag serialiseras för att skapa ett undantagstillståndsobjekt som innehåller serialiserade data om undantaget.

(Ärvd från Exception)

Gäller för