Class Configuration
- Namespace
- FishMMO.Shared
- Assembly
- FishMMO-SharedUtility.dll
Thread-safe key-value configuration store with file I/O, environment-variable override support, and typed accessors. Each instance manages its own lock so that multiple Configuration objects can be used independently without cross-instance contention.
public class Configuration : IDisposable
- Inheritance
-
Configuration
- Implements
- Inherited Members
Constructors
Configuration(string)
Initializes a new instance of the Configuration class with a specified default file directory. Throws an ArgumentNullException if the provided directory path is null or empty.
public Configuration(string defaultFileDirectory)
Parameters
defaultFileDirectorystringThe default directory where configuration files are saved and loaded.
Fields
DEFAULT_FILENAME
public const string DEFAULT_FILENAME = "Configuration"
Field Value
EXTENSION
public const string EXTENSION = ".cfg"
Field Value
FULL_NAME
public const string FULL_NAME = "Configuration.cfg"
Field Value
Properties
DefaultFileDirectory
Gets the default directory where configuration files are saved and loaded. This value is set during construction.
public string DefaultFileDirectory { get; }
Property Value
DisableFileIO
Set to true by the Unity host when running in a WebGL build. When true, file I/O operations will be skipped.
public static bool DisableFileIO { get; set; }
Property Value
FileName
Gets or sets the base name of the configuration file (without the extension). The getter acquires the read lock so that concurrent reads see a consistent value on ARM weak memory models. The setter acquires the write lock so that concurrent Save/Load calls see a consistent file name.
public string FileName { get; set; }
Property Value
GlobalSettings
Represents the globally accessible configuration instance. This should typically be set once at application startup. Thread-safe via Exchange(ref double, double) on the backing field.
public static Configuration? GlobalSettings { get; }
Property Value
Methods
Combine(Configuration)
Combines the settings from another configuration with this configuration.
Existing entries in this configuration will be overwritten by values from the 'other' configuration.
If the 'other' configuration is null, no changes are made.
If you want to merge without overwriting, you'll need different logic (e.g., settings.TryAdd).
public void Combine(Configuration other)
Parameters
otherConfigurationThe other configuration to combine with.
Dispose()
Disposes the ReaderWriterLockSlim used for thread-safe access.
public void Dispose()
Exists(string)
Checks if a setting with the specified name exists in the configuration.
public bool Exists(string name)
Parameters
namestringThe name of the setting to check.
Returns
- bool
True if the setting exists; otherwise, false.
GetKeys(string?)
Returns every setting name currently held, optionally restricted to those beginning
with prefix.
public List<string> GetKeys(string? prefix = null)
Parameters
prefixstringCase-insensitive prefix to filter by, or null/empty for every key.
Returns
Remarks
A copy, taken under the read lock, rather than a live view: the dictionary is mutated from other threads and callers walk this list while calling Set(string, string) and Remove(string) on the same instance, either of which would invalidate an enumerator taken over the dictionary itself.
Environment-variable overrides are deliberately NOT included. They are a deployment mechanism for individual known keys, not part of the stored configuration, and a caller enumerating keys is asking what this file holds.
Load(string)
Loads the configuration from the default file path, using the DefaultFileDirectory
and the provided fileName with the EXTENSION.
public bool Load(string fileName)
Parameters
fileNamestringThe name of the file (e.g., "Configuration.cfg").
Returns
- bool
True if the configuration was loaded successfully, false otherwise.
Load(string, string)
Loads the configuration from a specified file path. The file content is read as UTF-8, stripped of any BOM, and parsed into key-value pairs. Lines starting with '#' or ';' (after trimming whitespace) are ignored as comments. Includes robust error handling for file I/O and access exceptions.
public bool Load(string fileDirectory, string fullFileName)
Parameters
fileDirectorystringThe directory of the file.
fullFileNamestringThe full file name (e.g., "myconfig.cfg").
Returns
- bool
True if the configuration was loaded successfully, false otherwise.
Remove(string)
Removes a setting with the specified name from the configuration.
public bool Remove(string name)
Parameters
namestringThe name of the setting to remove.
Returns
- bool
True if the setting was successfully removed; otherwise, false if the setting was not found.
Save()
Saves the current configuration to the default file path, using the DefaultFileDirectory and FileName with the EXTENSION.
public void Save()
Save(string, string)
Saves the current configuration to a specified file path. Each setting is written as "key=value" on a new line. The file is created or truncated if it already exists, and encoded in UTF-8 without a Byte Order Mark (BOM). Includes error handling for common file I/O and access exceptions.
public void Save(string fileDirectory, string fullFileName)
Parameters
fileDirectorystringThe directory to save the file in.
fullFileNamestringThe full file name (e.g., "myconfig.cfg").
Set(string, double)
Sets a double value for a given setting name, formatted using the InvariantCulture. The "R" (Round-trip) format specifier is used to ensure precise and consistent serialization of the double value.
public void Set(string name, double value)
Parameters
Set(string, float)
Sets a float value for a given setting name, formatted using the InvariantCulture. The "R" (Round-trip) format specifier is used to ensure precise and consistent serialization.
public void Set(string name, float value)
Parameters
Set(string, string)
Sets a string value for a given setting name.
Throws an ArgumentNullException if the setting name is null or whitespace,
or if the value is null.
public void Set(string name, string value)
Parameters
SetGlobalSettings(Configuration)
Sets the global configuration instance. This method should typically be called once at application startup to initialize GlobalSettings. Throws an ArgumentNullException if the provided configuration instance is null.
public static void SetGlobalSettings(Configuration config)
Parameters
configConfigurationThe configuration instance to set as global.
SetOptional(string, string?)
Sets a string value for a given setting name, allowing null values.
If value is null, an empty string is stored.
Throws an ArgumentNullException if the setting name is null or whitespace.
public void SetOptional(string name, string? value)
Parameters
namestringThe name of the setting.
valuestringThe string value to set, or null to store an empty string.
Set<T>(string, T)
Sets a generic value for a given setting name by converting it to its string representation.
If the value is null, an empty string is stored.
public void Set<T>(string name, T value)
Parameters
namestringThe name of the setting.
valueTThe value to set.
Type Parameters
TThe type of the value.
Remarks
Every value is formatted with InvariantCulture, and that
is not a nicety. This used to call value.ToString(), which formats with the
current culture, while every reader below parses with the invariant one. On any
machine whose locale writes a comma as the decimal separator — most of Europe — a float
written here came back as a different number entirely: 0.75f was stored as
"0,75" and read back by TryGetFloat(string, out float, float), which accepted the comma as a
digit-group separator, as 75. Interface scale, brightness, every audio volume and
every window position round-tripped to roughly a hundred times their value and were then
clamped to whatever bound the reader enforced. The setting looked like it had not been
saved; in fact it had been saved and misread.
float and double take the round-trip ("R") format, so a stored value parses back to the identical bits. Everything else that knows how to format itself is asked to do so invariantly, which also keeps enum names, dates and negative signs stable across locales.
ToString()
Returns a string representation of the configuration, including its full file path and all stored key-value pairs for debugging purposes.
public override string ToString()
Returns
TryGetBool(string, out bool, bool)
Attempts to retrieve a boolean value from the configuration.
public bool TryGetBool(string name, out bool result, bool defaultValue = false)
Parameters
namestringThe name of the setting.
resultboolWhen this method returns, contains the boolean value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValueboolThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
TryGetByte(string, out byte, byte)
Attempts to retrieve a byte value from the configuration. Parsing is performed using Any and InvariantCulture.
public bool TryGetByte(string name, out byte result, byte defaultValue = 0)
Parameters
namestringThe name of the setting.
resultbyteWhen this method returns, contains the byte value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValuebyteThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
TryGetChar(string, out char, char)
Attempts to retrieve a char value from the configuration.
public bool TryGetChar(string name, out char result, char defaultValue = '\0')
Parameters
namestringThe name of the setting.
resultcharWhen this method returns, contains the char value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValuecharThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
TryGetDouble(string, out double, double)
Attempts to retrieve a double value from the configuration. Parsing is performed using Float and InvariantCulture.
public bool TryGetDouble(string name, out double result, double defaultValue = 0)
Parameters
namestringThe name of the setting.
resultdoubleWhen this method returns, contains the double value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValuedoubleThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
TryGetEnum<TEnum>(string, out TEnum, TEnum)
Attempts to retrieve an enum value of a specified type from the configuration. Parsing is case-insensitive.
public bool TryGetEnum<TEnum>(string name, out TEnum result, TEnum defaultValue = default) where TEnum : struct, Enum
Parameters
namestringThe name of the setting.
resultTEnumWhen this method returns, contains the enum value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValueTEnumThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
Type Parameters
TEnumThe type of the enum.
TryGetFloat(string, out float, float)
Attempts to retrieve a float value from the configuration. Parsing is performed using Float and InvariantCulture.
public bool TryGetFloat(string name, out float result, float defaultValue = 0)
Parameters
namestringThe name of the setting.
resultfloatWhen this method returns, contains the float value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValuefloatThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
TryGetInt(string, out int, int)
Attempts to retrieve an int value from the configuration. Parsing is performed using Any and InvariantCulture.
public bool TryGetInt(string name, out int result, int defaultValue = 0)
Parameters
namestringThe name of the setting.
resultintWhen this method returns, contains the int value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValueintThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
TryGetLong(string, out long, long)
Attempts to retrieve a long value from the configuration. Parsing is performed using Any and InvariantCulture.
public bool TryGetLong(string name, out long result, long defaultValue = 0)
Parameters
namestringThe name of the setting.
resultlongWhen this method returns, contains the long value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValuelongThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
TryGetSByte(string, out sbyte, sbyte)
Attempts to retrieve an sbyte value from the configuration. Parsing is performed using Any and InvariantCulture.
public bool TryGetSByte(string name, out sbyte result, sbyte defaultValue = 0)
Parameters
namestringThe name of the setting.
resultsbyteWhen this method returns, contains the sbyte value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValuesbyteThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
TryGetShort(string, out short, short)
Attempts to retrieve a short value from the configuration. Parsing is performed using Any and InvariantCulture.
public bool TryGetShort(string name, out short result, short defaultValue = 0)
Parameters
namestringThe name of the setting.
resultshortWhen this method returns, contains the short value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValueshortThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
TryGetString(string, out string?, string?)
Attempts to retrieve a string value from the configuration.
public bool TryGetString(string name, out string? result, string? defaultValue = null)
Parameters
namestringThe name of the setting.
resultstringWhen this method returns, contains the string value from the configuration, or the
defaultValueif the setting was not found.defaultValuestringThe value to return if the setting is not found.
Returns
- bool
True if the setting was found; otherwise, false.
TryGetUInt(string, out uint, uint)
Attempts to retrieve a uint value from the configuration. Parsing is performed using Any and InvariantCulture.
public bool TryGetUInt(string name, out uint result, uint defaultValue = 0)
Parameters
namestringThe name of the setting.
resultuintWhen this method returns, contains the uint value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValueuintThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
TryGetULong(string, out ulong, ulong)
Attempts to retrieve an ulong value from the configuration. Parsing is performed using Any and InvariantCulture.
public bool TryGetULong(string name, out ulong result, ulong defaultValue = 0)
Parameters
namestringThe name of the setting.
resultulongWhen this method returns, contains the ulong value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValueulongThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
TryGetUShort(string, out ushort, ushort)
Attempts to retrieve an ushort value from the configuration. Parsing is performed using Any and InvariantCulture.
public bool TryGetUShort(string name, out ushort result, ushort defaultValue = 0)
Parameters
namestringThe name of the setting.
resultushortWhen this method returns, contains the ushort value from the configuration, or the
defaultValueif the conversion failed or the setting was not found.defaultValueushortThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
TryGet<T>(string, out T, T)
Attempts to retrieve a value of a specified type from the configuration.
This is a generic method that uses ChangeType(object, Type).
Specific TryParse methods (e.g., TryGetInt(string, out int, int)) are generally preferred for primitive types due to better error handling
and performance for specific types.
Logs warnings to the console for InvalidCastException, FormatException, or OverflowException
that occur during the conversion process.
public bool TryGet<T>(string name, out T result, T defaultValue = default) where T : IConvertible
Parameters
namestringThe name of the setting.
resultTWhen this method returns, contains the value from the configuration, if the conversion succeeded, or the
defaultValuefor the type if the conversion failed or the setting was not found.defaultValueTThe value to return if the setting is not found or cannot be converted.
Returns
- bool
True if the setting was found and successfully converted; otherwise, false.
Type Parameters
TThe type to convert the setting value to. Must implement IConvertible.