views:

1346

answers:

8

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

I am unclear on how i can store a dictionary as a setting. I see that under system.collections.special there is a thing called a stringdictionary but ive read that SD are outdated and shouldn't be used.

also in the future i may have need to store a dictionary that is not strings only (int string)

how would you store a dictionary in the settings file for a .net application?

+7  A: 

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.

David
Good idea - use something like JSON serialization to make this process relatively painless.
Erik Forbes
could you elborate on that a little?
Crash893
JSON serialization is of the form {"object": { "key": "value", "key": "value" } }
Chris Kaminski
How would i do that?Im thinking i could just do a foreach loop of each key value pair into a string then save the string or something but i would like to do this as correctly as possible
Crash893
There are JSON serialization libraries out there in the wild - you don't have to do this from scratch; but if you wanted to, it shouldn't be too hard to write up a very simple one.
Erik Forbes
http://www.json.org/
Erik Forbes
+2  A: 

Other than doing something like David's suggests, I would look into alternate storage for the Dictionary. Ultimately the Settings object serializes to disk.

Erik Forbes
+1  A: 

You could create a custom class that exposes a Dictionary as a public property. Then you can specify this custom type as the type for your setting.

Edit:

I have just read that, for some reason, a generic dictionary cannot be XML-serialized, so my solution will probably not work (I haven't tested it though...). That's strange, because a generic list can be serialized without any problem.

You could still create a custom class that can be set as a user setting, but you will need to have a list exposed as a property instead of a dictionary.

Meta-Knight
I'm not sure i follow. create a class that contains a dictionary then save that class?
Crash893
Exactly, but because generic dictionary is not serializable (see edit) it would need to be a list instead.
Meta-Knight
+1  A: 

Have you considered using XML to store your dictionary? That would provide a certain amount of extensibility if in the future you decide you want to be able to store other types of dictionaries. You might do something like:

<dictionary>
   <entry key="myKey">
      [whatever data you like]
   </entry>
</dictionary>

Might be overkill, but you'd also be prepared in the case that you wanted to store more complex data, like custom objects.

Ender
+1  A: 

XML Serializable Generic Dictionary

DGGenuine
A: 

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);
}
Olivier de Rivoyre
A: 

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.

Brad
A: 

You can store a StringCollection. It is similar to this solution.

I made 2 extension methods to convert between StringCollection and a Dictionary. This is the easiest way I could think of.

public static class Extender
{
    public static Dictionary<string, string> ToDictionary(this StringCollection sc)
    {
        if (sc.Count % 2 != 0) throw new InvalidDataException("Broken dictionary");

        var dic = new Dictionary<string, string>();
        for (var i = 0; i < sc.Count; i += 2)
        {
            dic.Add(sc[i], sc[i + 1]);
        }
        return dic;
    }

    public static StringCollection ToStringCollection(this Dictionary<string, string> dic)
    {
        var sc = new StringCollection();
        foreach (var d in dic)
        {
            sc.Add(d.Key);
            sc.Add(d.Value);
        }
        return sc;
    }
}

class Program
{
    static void Main(string[] args)
    {
        //var sc = new StringCollection();
        //sc.Add("Key01");
        //sc.Add("Val01");
        //sc.Add("Key02");
        //sc.Add("Val02");

        var sc = Settings.Default.SC;

        var dic = sc.ToDictionary();
        var sc2 = dic.ToStringCollection();

        Settings.Default.SC = sc2;
        Settings.Default.Save();
    }
}
BrunoLM