Search code examples
c#saveread-write

Write/Read Text Files (C#)


I wasn't 100% sure how to explain this in the title or how to search it up, so sorry if this has been post before. What I'm trying to do is read and write a file, for example I would do:

WriteToFile(key + "=" + value);

And in the text file it would say something like:

AKey=AValue

I was able to get that fairly easily but I was wonder how exactly would I get code to find that 'key' and return its value. For example:

int integer = GetValue("AKey");

And the method GetValue would find the 'key', "AKey", and if it existed in the file, return the value.


Solution

  • 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).