This question already has an answer here:
I'm trying to save a class into an XML Document. The class looks Like this:
public class Settings
{
public LDAP LDAP;
public Miscellaneous Miscellaneous;
}
public class LDAP
{
public bool LoadLDAPData;
public bool ShowLDAPRoutingMessage;
}
public class Miscellaneous
{
public bool MinusBeforeQuestion;
public bool MinusBeforeDescription;
}
The Data ist stored via this:
Settings MySettings = new Settings();
string MySettingsFile = @"settingsfile.xml";
...
FileStream outFile = File.Open(MySettingsFile, FileMode.OpenOrCreate);
XmlSerializer formatter = new XmlSerializer(MySettings.GetType());
formatter.Serialize(outFile, MySettings);
outFile.Close();
The Data is saved, but with one issue at the end:
<Settings...>
...
</Settings>>>
Can you tell me why?
This is happening because the content you are writing is shorter than the existing contents of the file, so some of the text is left at the end.
Instead of
FileMode.OpenOrCreate
(which opens the file and leaves its content intact if the file exists), useFileMode.Create
:Description of
FileMode.Create
: