How do I store an array of a particular type into my settings file?
Asked Answered
N

2

2

For some reason, I can't seem to store an array of my class into the settings. Here's the code:

            var newLink = new Link();
            Properties.Settings.Default.Links = new ArrayList();
            Properties.Settings.Default.Links.Add(newLink);
            Properties.Settings.Default.Save();

In my Settings.Designer.cs I specified the field to be an array list:

    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    public global::System.Collections.ArrayList Links {
        get {
            return ((global::System.Collections.ArrayList)(this["Links"]));
        }
        set {
            this["Links"] = value;
        }
    }

For some reason, it won't save any of the data even though the Link class is serializable and I've tested it.

Nephogram answered 3/5, 2010 at 23:41 Comment(5)
"I can't seem" How do you see that? Is an exception thrown? Is the list empty when loading? Is is empty without reloading?Chowchow
The list is empty with no exceptions thrown. Somehow it isn't serializing my Links.Nephogram
Is the data contained in the settings file (it's an XML file so you can easily check)?Chowchow
I checked the user.config and there are no Links contained in the array.Nephogram
Here's the user.config file: <?xml version="1.0" encoding="utf-8"?> <configuration> <userSettings> <AdminTool.Properties.Settings> <setting name="Links" serializeAs="Xml"> <value /> </setting> </AdminTool.Properties.Settings> </userSettings> </configuration> Interestingly, I tried to write an array of integers and it worked fine. I wonder what gives?Nephogram
N
3

I found the source of the problem. Simply using a plain Array won't cut it. After thinking about it, the deserializer wouldn't know what type to deserialize the array items to. I failed to see that the array required strong typing. The designer lead me to foolishly believe it was a plain generic array:

    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    public List<Link> Links
    {
        get {
            return ((List<Link>)(this["Links"]));
        }
        set {
            this["Links"] = value;
        }
    }

I had to make these changes in the Settings.Designer.cs and not from the designer.

Nephogram answered 5/5, 2010 at 2:42 Comment(0)
C
1

Make sure that your Link class is either correctly XML-serializable or that it has a typeconverter to string (which is preferred when using application.settings files).

I'd assume that something in your types will not transform into the XML-serialization format. And your user.config shows that it doesn't have any string typeconverter available.

Chowchow answered 4/5, 2010 at 0:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.