For the sake of complete-ness, I'll expand on my comment, here is some example code of how you would accomplish this:
Dictionary<string, string> _keys = new Dictionary<string, string>();
private void ReadInKeyFile(string keyFileName)
{
_keys.Clear();
string[] lines = System.IO.File.ReadAllLines(keyFileName);
foreach (string line in lines)
{
string[] keyval = line.Split('=');
_keys.Add(keyval[0], keyval[1]);
}
}
private string GetValue(string key)
{
string retVal = string.Empty;
_keys.TryGetValue(key, out retVal);
return retVal;
}
The Dictionary<string, string>
holds the key/value pairs that are read in from the file, so when you want to refresh it, you would call the ReadInKeyFile
function with the file name. You can then use GetValue
to get the value for a particular key (or String.Empty
if the key is not found).
There are some obvious checks that I'm missing in the code above (file doesn't exist, line doesn't contain a =
, etc), but it gets you 90% of the way there.
Edit
Here is some extensions to that for adding new keys and writing it out to a file:
private void SaveKeysToFile(string keyFileName)
{
StringBuilder sb = new StringBuilder();
_keys.ToList().ForEach(kvp =>
sb.AppendLine(string.Format("{0}={1}", kvp.Key, kvp.Value)));
System.IO.File.WriteAllText(keyFileName, sb.ToString());
}
private void AddValue(string key, string value)
{
_keys[key] = value;
}
The SaveToFile
method converts the dictionary to the file format you use, and the AddValue
adds a key and value (or changes the existing key if it already exists).