I'm trying to load some AppSettings into an object. The settings look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Logging_default_path" value="C:\Temp" />
<add key="Logging_max_file_size" value="10485760" />
<add key="Logging_levels" value="Error,Warning,Info"/>
<add key="Logging_filename" value="RobinsonLog" />
</appSettings>
</configuration>
The Logging_levels represents several enum values that are allowed by the settings. I'm trying to load these into my object by using the following code:
Level = (LogLevel)Enum.Parse(typeof(LogLevel), settings["Logging_levels"]);
But this is not working and I'm only getting LogLevel.Info returned, not the value of Loglevel.Error | LogLevel.Warning | LogLevel.Info. The enum is defined as followed:
[Flags]
public enum LogLevel
{
Error = 0x0,
Warning = 0x1,
Info = 0x2,
Debug = 0x3,
Performance = 0x4
}
Am I wrong by defining the values in hex? or did I miss something else?
If the parse operation fails, the result parameter contains the default value of 0, which may not be a member of the underlying TEnum enumeration. If no values are assigned to the named constants in TEnum , the default is equal to the first member of the TEnum .
You can create Enum from String by using Enum. valueOf() method. valueOf() is a static method that is added on every Enum class during compile-time and it's implicitly available to all Enum along with values(), name(), and cardinal() methods.
Enum's in . Net are integral types and therefore any valid integral value can be cast to an Enum type. This is still possible even when the value being cast is outside of the values defined for the given enumeration!
Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.
Your enum
values are going to cause problems.
The values of a Flags
enum
must be powers of two, and you shouldn't use 0 for any value other than some kind of empty/none/nothing indicator.
Does this make any difference?
[Flags]
public enum LogLevel
{
None = 0
Error = 1,
Warning = 2,
Info = 4,
Debug = 8,
Performance = 16
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With