本文介绍了文件存在时FileMode.Open和FileMode.OpenOrCreate的区别? C#错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了以下代码:

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);
    }
}

当我使用 FileMode时.Open 一切都很好,输出是ex像这样:

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>

但是当我将其更改为 FileMode.OpenOrCreate 输出将更改为:

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

是什么使整个xml文件由于附加的>

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

这是可解释的还是它的c#错误?

Is this explanable or its c# bug?

推荐答案

我刚刚转载了该问题。
正如我在评论中写道。

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

似乎文件的新内容比以前短一个字符这就是为什么在末尾看到>的原因。

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

如果要编写文件,请使用 FileMode.Create 应该为您做。

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

这篇关于文件存在时FileMode.Open和FileMode.OpenOrCreate的区别? C#错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 16:49