I want to create a dictionary from a settings file that is formatted as a list of strings "somekey = somevalue". I then want this dictionary of keys and values, generated by one class, to be available to other classes in my program, so I don't have to refer back to the external file every time I want to use the settings in another class.
I've figured out the first part, creating a class that can read an external file and convert the list of strings into a dictionary, but I can't figure out how to make the dictionary data created by the file-reading class available to other classes in the same namespace.
A little different approach would be to use an extension method, my example is rather basic but it works perfectly
using System.Collections.Generic;
namespace SettingsDict
{
class Program
{
static void Main(string[] args)
{
// call the extension method by adding .Settings();
//Dictionary<string, string> settings = new Dictionary<string, string>().Settings();
// Or by using the property in the Constants class
var mySettings = Constants.settings;
}
}
public class Constants
{
public static Dictionary<string, string> settings
{
get
{
return new Dictionary<string, string>().Settings();
}
}
}
public static class Extensions
{
public static Dictionary<string, string> Settings(this Dictionary<string, string> myDict)
{
// Read and split
string[] settings = System.IO.File.ReadAllLines(@"settings.txt");
foreach (string line in settings)
{
// split on =
var split = line.Split(new[] { '=' });
// Break if incorrect lenght
if (split.Length != 2)
continue;
// add the values to the dictionary
myDict.Add(split[0].Trim(), split[1].Trim());
}
return myDict;
}
}
}
Contents of settings.txt
setting1=1234567890
setting2=hello
setting3=world
And the result
You should of course extend this with your own protective features and similar. This is an alternative approach but using extension methods is not that bad. The functionality in the Extensions class can also be implemented directly in the property method in the Constants class. I did that for the fun of it :)
Just make the class that constins the dictoionary public and the dictionary in that class static, so
public class MyClass
{
// ...
public static Dictionary<string, string> checkSumKeys { get; set; }
// ...
}
call this like
// ...
foreach (KeyValuePair<string, string> checkDict in MyClass.checkSumKeys)
// Do stuff...
Or, if the dictionary is not made static you will have to instantiate the class
public class MyClass
{
// ...
public Dictionary<string, string> checkSumKeys { get; set; }
// ...
}
call this like
MyClass myclass = new MyClass();
foreach (KeyValuePair<string, string> checkDict in myClass.checkSumKeys)
// Do stuff...
I hope this helps.
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