• 0

[C#] Saving custom ConfigurationSection


Question

Im having some trouble saving to the App.Config...

This is the desired App.Config output:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>
		<section name="Logging" type="MyCustomConfig.LoggingConfigSection, MyCustomConfig" />
	</configSections>
	<Logging>
		<Exception path=".\" />
	</Logging>
</configuration>

These are the custom Configuration classes:

	public class LogConfigElement : ConfigurationElement
	{
		private LogConfigElement()
		{
		}

		[ConfigurationProperty("path", DefaultValue = @".\", IsRequired = true)]
		[StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|", MinLength = 1)]
		public string Path
		{
			get { return (string)this["path"]; }
			set { this["path"] = value; }
		}
	}

	public class LoggingConfigSection : ConfigurationSection
	{
		public LoggingConfigSection()
		{
		}

		[ConfigurationProperty("Exception", IsRequired = true)]
		public LogConfigElement Exception
		{
			get { return (LogConfigElement)this["Exception"]; }
		}
	}

This is the code to load and save to the App.Config:

			Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
			Logging = (LoggingConfigSection)config.Sections["Logging"];
			if (Logging == null)
			{
				Logging = new LoggingConfigSection();
				[b]//Logging.Exception.Path = Logging.Exception.Path;[/b]
				config.Sections.Add("Logging", Logging);
				config.Save();
				ConfigurationManager.RefreshSection("Logging");
			}

Loading the App.Config values works fine. Saving changes to the App.Config values works fine. However, if the App.Config is empty the code does not save the default values to the App.Config - it only writes the config sections part like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>
		<section name="Logging" type="MyCustomConfig.LoggingConfigSection, MyCustomConfig" />
	</configSections>
</configuration>

When I uncomment the following line it will save the values to the App.Config. Can someone explain what im doing wrong... why does it not save the default values. Why do i have to force a change on the object before it will write to the App.Config?

[b]//Logging.Exception.Path = Logging.Exception.Path;[/b]

Thanks for any help you can give!

Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.