C# Configuration Custom Section – Configuration Element

Recently I needed a custom section in my app.config. Everything went fine until I got this exception:
“The string must be at least 1 characters long.” (System.Configuration.ConfigurationErrorsException type) while reading the custom section…..

My code in app.config look like this:

<projectSection>
<projects>
<project ProjectID="1" ExternalProjectID="W30091" />
</projects>
</projectSection>

and everything was fine with it…

Below is C# that was responsible for throwing exception:

public class ProjectElement : ConfigurationElement
{
    [ConfigurationProperty("ProjectID",  IsRequired = true)]
    [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'"|", MinLength = 1, MaxLength = 60)]
    public String ProjectID
    {
    get { return (String)this["ProjectID"]; }
    set { this["ProjectID"] = value; }
}

ProjectSection config = (ProjectSection)System.Configuration.ConfigurationManager.GetSection("projectSection");

At the start this exception seemed little bit stupid, but…… Because i’m using StringValidation attribute in my property I’ve to add DefaultValue="some_value" initial parameter to ConfigurationProperty attribute…..
After deeper investigation I found here a reasonable answer.

Follow me:

Leave a Reply

Your email address will not be published. Required fields are marked *