Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

xml - FileMode.Open and FileMode.OpenOrCreate difference when file exists? c# bug?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...