Question

I have a service that needs to receive configuration from APP config to make it easier to update when you need to change the search criterias - for example if error occurs. so, saying that I would like to know how to set a Datetime value in app.config

I want something like:

<add key="MyDate" value="DateTime.Now" />
Was it helpful?

Solution

If you want to default this setting to DateTime.Now, or to allow a specific value to be specified, then you probably want some code like this:

Dim magicDate = If(Not String.IsNullOrWhiteSpace(
                       ConfigurationManager.AppSettings("OverrideMagicDate")),
         Date.Parse(ConfigurationManager.AppSettings("OverrideMagicDate")),
         Date.Now)

And now in app.settings you leave the OverrideMagicDate setting value empty to get DateTime.Now or you supply a specific date.

<add key="OverrideMagicDate" value="" /><!-- DateTime.Now -->

or:

<add key="OverrideMagicDate" value="2012-01-13" /><!-- 13th Jan 2012 -->

You might need to switch Parse to ParseExact if you want more control over what format of dates you accept.

OTHER TIPS

Example in C#:

app.config

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="MyDate" value="2014-01-01" />
  </appSettings>
</configuration>

In the form... with DateTimePicket and Button generates for example:

private void bChange_Click(object sender, EventArgs e)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    AppSettingsSection app = config.AppSettings;
    app.Settings["MyDate"].Value = this.dtMyDate.Value.ToShortDateString();
    config.Save(ConfigurationSaveMode.Modified);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top