Serializing XML file produces invalid XML document (11,12)

I am trying to store a class in 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;
}

      

Data is stored through 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();

      

Data persists, but with one problem at the end:

<Settings...>
...
</Settings>>>

      

Can you tell me why?

+1


source to share


1 answer


This is because the content you are writing is shorter than the existing file content, so some of the text remains at the end.

Instead FileMode.OpenOrCreate

(which opens the file and leaves its contents intact if the file exists), use FileMode.Create

:

FileStream outFile = File.Open(MySettingsFile, FileMode.Create);

      



Description FileMode.Create

:

Indicates that the operating system should create a new file. If the file already exists, it will be overwritten. This requires the FileIOPermissionAccess.Write permission. FileMode.Create is equivalent to asking if file doesn't exist, use CreateNew; otherwise use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException is thrown.

+2


source







All Articles