I am using .Net 2 and the normal way to store my settings. I store my custom object serialized to xml. I am trying to retrieve the default value of the property (but without reseting other properties). I use:
ValuationInput valuationInput = (ValuationInput) Settings.Default.Properties["ValuationInput"].DefaultValue;
But it seems to return a string instead of ValuationInput and it throws an exception.
I made a quick hack, which works fine:
string valuationInputStr = (string)
Settings.Default.Properties["ValuationInput"].DefaultValue;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(ValuationInput));
ValuationInput valuationInput = (ValuationInput) xmlSerializer.Deserialize(new StringReader(valuationInputStr));
But this is really ugly - when I use all the tool to define a strongly typed setting, I don't want to serialize the default value myself, I would like to read it the same way as I read the current value: ValuationInput valuationInput = Settings.Default.ValuationInput;
At some point, something, somewhere is going to have to use Xml Deserialization, whether it is you or a wrapper inside the settings class. You could always abstract it away in a method to remove the "ugly" code from your business logic.
public static T FromXml<T>(string xml)
{
XmlSerializer xmlser = new XmlSerializer(typeof(T));
using (System.IO.StringReader sr = new System.IO.StringReader(xml))
{
return (T)xmlser.Deserialize(sr);
}
}
http://www.vonsharp.net/PutDownTheXmlNodeAndStepAwayFromTheStringBuilder.aspx
@Grzenio,
Why don't you use your object type directly? You can set type of your setting on Project Properties->Settings tab. You can select your type by clicking on Browse in drop down for Type column.
Citation from MSDN:
Application settings can be stored as any data type that is XML serializable or has a TypeConverter that implements ToString/FromString
That way you can have strongly typed settings, ie (ValuationInput) Settings.Default.Properties["ValuationInput"].DefaultValue; will return an object instead of string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.