My goal is to be able to share configration settings amongst apps. For example I want to be able to use a WinForm app to set and save the settings and have a console app be able to read those settings and run as a scheduled task. The approach I tried is to create a SharedSettings class that is referenced by both the Winform app and the Console app. In this class there is nothing but public string properties like so.
public class SharedSettings
{
public string URL { get; set; }
public string DestUser { get; set; }
public string RelScript { get; set; }
}
I am using the following to serialize the instance of the SharedSettings class
SharedSettings settings = new SharedSettings();
settings.RelScript = this.txtRelScript.Text;
settings.URL = this.txtURL.Text;
settings.DestUser = this.txtDestUser.Text;
XmlSerializer dehydrator = new XmlSerializer(settings.GetType());
System.IO.FileStream fs = new FileStream(this.configFilePath, FileMode.OpenOrCreate);
dehydrator.Serialize(fs, settings);
and this to Deserialize it and populate the fields in the Form
SharedSettings settings = new SharedSettings();
XmlSerializer dehydrator = new XmlSerializer(settings.GetType());
System.IO.FileStream fs = new FileStream(this.configFile, FileMode.Open);
settings = (SharedSettings)dehydrator.Deserialize(fs);
this.txtRelScript.Text = settings.RelScript;
this.txtURL.Text = settings.URL;
this.DestUser.Text = settings.DestUser;
Every once in a while maybe one out of every five times I run it the XML file that is created in not valid XML. Here is an example
<?xml version="1.0"?>
<SharedSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ProjectName>test2</ProjectName>
<URL />
<DestUser>test3</DestUser>
<RelScript>D:\Events.dll</ReleaseScript>
</SharedSettings>ttings>
Notice the last line. ttings> What am I doing wrong in Serializing my class?
It looks like the previous run through wrote out a longer file. The use of FileMode.OpenOrCreate
in your serialization code doesn't truncate the previous file, so it is partly overwritten.
Use FileMode.Create
instead.
See the documentation here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With