Store Dictionary in application settings

后端 未结 9 1611
感动是毒
感动是毒 2020-11-30 08:28

I have a dictionary of strings that i want the user to be able to add/remove info from then store it for them so it they can access it the next time the program restarts

相关标签:
9条回答
  • 2020-11-30 09:05

    Edit: This will return a Hashtable (for whatever reason, despite being a 'DictionarySectionHandler'). However, being that Hashtables and Dictionaries are so similar, it shouldn't be a large issue (though I realize Dictionaries are newer, parameterized, etc; I would have preferred dicitonaries myself, but this is what .NET gives us).


    The best answer I just found for this is here. It returns a typesafe collection witout any muddling in code to transform it, and you create an obvious (and simple) collection in your .config file. I'm using this and it's quite straight forward for any future programmer (including yourself). It allows for stronger typing and more flexibility, without any overly-complicated and unnecessary parsing.

    0 讨论(0)
  • 2020-11-30 09:13

    You can also use a System.Collections.Specialized.StringCollection by putting key on even index and values on odd index.

    /// <summary>
    /// Emulate a Dictionary (Serialization pb)
    /// </summary>
    private static string getValue(System.Collections.Specialized.StringCollection list, string key)
    {
        for (int i = 0; i * 2 < list.Count; i++)
        {
            if (list[i] == key)
            {
                return list[i + 1];
            }
        }
        return null;
    }
    
    /// <summary>
    /// Emulate a Dictionary (Serialization pb)
    /// </summary>      
    private static void setValue(System.Collections.Specialized.StringCollection list, string key, string value)
    {
        for (int i = 0; i * 2 < list.Count; i++)
        {
            if (list[i] == key)
            {
                list[i + 1] = value;
                return;
            }
        }
        list.Add(key);
        list.Add(value);
    }
    
    0 讨论(0)
  • 2020-11-30 09:16

    The simplest answer would be to use a row & column delimiter to convert your dictionary to a single string. Then you just need to store 1 string in the settings file.

    0 讨论(0)
提交回复
热议问题