Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Optional fields in application settings

Tags:

c#

settings

Is there a way to create some optional fields in application settings. For example for one client we need some client based settings in the settings file, something like this:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <userSettings>
      <setting name="Client_1_out_folder" serializeAs="String">
        <value>c:\</value>
      </setting>
      <setting name="Some_other_setting" serializeAs="String">
        <value>True</value>
      </setting>
      ...

And for the other client we dont need the Client_1_out_folder at all so to keep the config file clean would be nice to remove it from the config file all together. So for client 2 that part of config file would look like:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <userSettings>
      <setting name="Some_other_setting" serializeAs="String">
        <value>True</value>
      </setting>
      ...
like image 868
hs2d Avatar asked Jul 06 '11 07:07

hs2d


2 Answers

Create a custon configuration section for your settings. Then on the configurationsection class, mark the property as "IsRequired=false" to make that property optional.

[ConfigurationProperty("frontPagePostCount"
    , DefaultValue = 20
    , IsRequired = false)]
like image 198
Jorge Córdoba Avatar answered Sep 22 '22 00:09

Jorge Córdoba


You can create a class which inherits from ConfigurationSection.

Then, you can do practically whatever you want. It's much more powerful than the user settings.

MSDN: How to: Create Custom Configuration Sections Using ConfigurationSection

You can extend ASP.NET configuration settings with XML configuration elements of your own. To do this, you create a custom configuration section handler. The handler must be a .NET Framework class that inherits from the System.Configuration.ConfigurationSection class. The section handler interprets and processes the settings that are defined in XML configuration elements in a specific section of a Web.config file. You can read and write these settings through the handler's properties.

The article says "ASP.NET", but it's not just for ASP.NET. It works equally well for WinForms.

like image 41
Steve Avatar answered Sep 21 '22 00:09

Steve