Expanding upon my earlier problem, I've decided to (de)serialize my config file class which worked great.
I now want to store an associative array of drive letters to map (key is the drive letter, value is the network path) and have tried using Dictionary
, HybridDictionary
, and Hashtable
for this but I always get the following error when calling ConfigFile.Load()
or ConfigFile.Save()
:
There was an error reflecting type 'App.ConfigFile'. [snip] System.NotSupportedException: Cannot serialize member App.Configfile.mappedDrives [snip]
From what I've read Dictionaries and HashTables can be serialized, so what am I doing wrong?
[XmlRoot(ElementName="Config")]
public class ConfigFile
{
public String guiPath { get; set; }
public string configPath { get; set; }
public Dictionary<string, string> mappedDrives = new Dictionary<string, string>();
public Boolean Save(String filename)
{
using(var filestream = File.Open(filename, FileMode.OpenOrCreate,FileAccess.ReadWrite))
{
try
{
var serializer = new XmlSerializer(typeof(ConfigFile));
serializer.Serialize(filestream, this);
return true;
} catch(Exception e) {
MessageBox.Show(e.Message);
return false;
}
}
}
public void addDrive(string drvLetter, string path)
{
this.mappedDrives.Add(drvLetter, path);
}
public static ConfigFile Load(string filename)
{
using (var filestream = File.Open(filename, FileMode.Open, FileAccess.Read))
{
try
{
var serializer = new XmlSerializer(typeof(ConfigFile));
return (ConfigFile)serializer.Deserialize(filestream);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.ToString());
return new ConfigFile();
}
}
}
}
You can use ExtendedXmlSerializer. If you have a class:
and create instance of this class:
You can serialize this object using ExtendedXmlSerializer:
Output xml will look like:
You can install ExtendedXmlSerializer from nuget or run the following command:
Here is online example
You can't serialize a class that implements IDictionary. Check out this link.
So I think you need to create your own version of the Dictionary for this. Check this other question.
You should explore Json.Net, quite easy to use and allows Json objects to be deserialized in Dictionary directly.
james_newtonking
example:
I wanted a SerializableDictionary class that used xml attributes for key/value so I've adapted Paul Welter's class.
This produces xml like:
Code:
Unit Tests:
Dictionaries and Hashtables are not serializable with
XmlSerializer
. Therefore you cannot use them directly. A workaround would be to use theXmlIgnore
attribute to hide those properties from the serializer and expose them via a list of serializable key-value pairs.PS: constructing an
XmlSerializer
is very expensive, so always cache it if there is a chance of being able to re-use it.There is a solution at Paul Welter's Weblog - XML Serializable Generic Dictionary