Search code examples
c#timespanconfigurationsection

TimeSpan of days in configuration?


It appears that ConfigurationElement of TimeSpan can't handle values larger than 23:59:59. Are there any workarounds? Is subclassing TimeSpan, and making a new TimeSpanValidatorAttribute even going to work? I need to handle timespans from a few minutes to a few days.

I'm using the following configuration section

[ConfigurationProperty("SequenceRolloverDOSCompare", IsRequired = true)]
[TimeSpanValidator(MinValueString = "0:0:00", MaxValueString = 10675199.02:48:05.4775807", ExcludeRange = false)]
public TimeSpan SequenceRolloverDOSCompare
{
    get
    {
        return (TimeSpan)base["SequenceRolloverDOSCompare"];
    }
}

with config looking like this:

<SequenceRolloverPolling SequenceRolloverDOSCompare="2:00:00:00"  />

gives ConfigurationErrorsException : The value of the property 'SequenceRolloverDOSCompare' cannot be parsed. The error is: 2:00:00:00 is not a valid value for TimeSpan.

or this:

<SequenceRolloverPolling SequenceRolloverDOSCompare="48:00:00"  />

gives OverflowException : The TimeSpan could not be parsed because at least one of the hours, minutes, or seconds components is outside its valid range


Solution

  • Use the . separator between days and hours:

    <SequenceRolloverPolling
        SequenceRolloverDOSCompare="2.00:00:00" />
    

    The TimeSpan format is defined as:

    ... [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second.