Serializing to XML file creates invalid XML docume

2019-07-25 09:54发布

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?

1条回答
做自己的国王
2楼-- · 2019-07-25 10:35

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), use FileMode.Create:

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

Description of FileMode.Create:

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

查看更多
登录 后发表回答