FileMode.Open and FileMode.OpenOrCreate difference when file exists? C # error?

I wrote this 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 use FileMode.Open

everything is fine and the output is ex for example:

<?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

, the output changes 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>>

      

which makes the whole XML file corrupted due to the extra character >

at the end.

Is this explainable or is it a C # bug?

+3


source to share


1 answer


I have just reproduced this issue. As I wrote in the comment.

FileMode.Open

erases the contents of the file, but FileMode.OpenOrCreate

not.



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

If you are writing a file, use FileMode.Create

which should do for you.

+3


source







All Articles