5

I have wrote that code:

public void Save()
{
    using (FileStream fs = new FileStream(Properties.Settings.Default.settings_file_path, FileMode.Open))
    {
        XmlSerializer ser = new XmlSerializer(typeof(MySettings));
        ser.Serialize(fs, this);
    }
}

When I am using FileMode.Open everything is good, and output is e.x. like this:

<?xml version="1.0"?>
<MySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <settingsList>
        <Setting>
            <Value>12</Value>
            <Name>A0</Name>
            <Type>MEASUREMENT</Type>
        </Setting>
        <Setting>
            <Value>5000</Value>
            <Name>C0</Name>
            <Type>MEASUREMENT</Type>
        </Setting>
    </settingsList>
</MySettings>

but when I change it to FileMode.OpenOrCreate output will change to:

<?xml version="1.0"?>
<MySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <settingsList>
        <Setting>
            <Value>12</Value>
            <Name>A0</Name>
            <Type>MEASUREMENT</Type>
        </Setting>
        <Setting>
            <Value>5000</Value>
            <Name>C0</Name>
            <Type>MEASUREMENT</Type>
        </Setting>
    </settingsList>
</MySettings>>

what makes whole xml file corrupted because of additional > sign at the end.

Is this explanable or its c# bug?

  • @GrantWinney Agree. FileModel.OpenOrCreate does not truncate the file. So writing to existing file may cause such behavior. – sszarek Apr 22 '15 at 13:49
  • Possible duplicate of [Deserialize an XML file - an error in xml document (11,12)](http://stackoverflow.com/questions/42270186/deserialize-an-xml-file-an-error-in-xml-document-11-12) – JLRishe Feb 16 '17 at 09:57

1 Answers1

7

I have just reproduced that issue. As I wrote in comment.

FileMode.Open erases contents of the file while FileMode.OpenOrCreate does not.

It seems that new content of the file is one char shorter than previous that's why you see ">" at the end.

If you are writing the file use FileMode.Create that should do for you.

shA.t
  • 16,580
  • 5
  • 54
  • 111
sszarek
  • 434
  • 2
  • 12
  • Thanks for reply. As i wrote- FIle.Open works perfectly for me but I was supposing that when file exists FIle.OpenOrCreate should work in the same way as FIle.Open and this post is about that – Robert Rudnicki Apr 22 '15 at 14:03
  • 1
    It does not and according to [link](https://msdn.microsoft.com/en-us/library/system.io.filemode(v=vs.110).aspx) it is "as designed" behavior. – sszarek Apr 22 '15 at 14:04