I have a Dictionary<MyType> that I want to store in my User settings in user.config. I know that Dictionary<MyType> is not serializable so I've tried to implement ISerializable on Dictionary<MyType> to serialize Dictionary<MyType> as a List<MyType> but this doesn't seem to work (even though I can get List<MyType> to serialize to app.config directly).
What am I missing?
Here's my code:
using System; using System.Collections.Generic; using System.Text; using System.Runtime.Serialization; namespace MyStuff { // Settings of type Deployment serialize to user.config with no problem [Serializable] public class Deployment { private string _Key; private string _ShortName; private string _Name; private string _URL; public Deployment() { } public Deployment(string key, string shortName, string name, string uRL) { _Key = key; _ShortName = shortName; _Name = name; _URL = uRL; } public string Key { get; set; } public string ShortName { get; set; } public string Name { get; set; } public string URL { get; set; } } // Settings of type DeploymentList serialize to user.config with no problem [Serializable()] public class DeploymentList : List<Deployment> { public DeploymentList() { } public DeploymentList(Deployment deployment) { this.Add(deployment); } } // - Breakpoints in GetObjectData and the constructor never seem to get hit // - Although I see the root of Deployments in user.config when I save it, // the DeploymentList property contained by Deployments doesn't get serialized public class Deployments: Dictionary<string, Deployment>, ISerializable { public Deployments() { } public DeploymentList dl; public Deployments(SerializationInfo info, StreamingContext context) { dl = (DeploymentList)info.GetValue("DeploymentList", typeof(DeploymentList)); foreach (Deployment d in dl) { this.Add(d.Key, d); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { dl = new DeploymentList(); foreach (Deployment d in this.Values) { dl.Add(d); } info.AddValue("DeploymentList", dl, typeof(DeploymentList)); } } }
Here's what I end up with in my app.config file:
<?xml version="1.0" encoding="utf-8"?><configuration><userSettings><MyStuff.Properties.Settings><setting name="DeploymentList" serializeAs="Xml"><value><ArrayOfDeployment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Deployment><Key>Test</Key><ShortName>Test</ShortName><Name>Test</Name><URL>http://test.com</URL></Deployment> </ArrayOfDeployment></value></setting><setting name="Deployments" serializeAs="Xml"><value /></setting></MyStuff.Properties.Settings></userSettings></configuration>