开发者

.net xmlserializer error

The error is when the class gets serialized, I don't get a run time error or anything (unless I try to deserialize). When the XmlSerializer serializes my class, some times it adds some text at then end of the XML. This happens often at the very end:

</RootNode>ootNode>

Some times it's not at the end but in the middle, something like

<Node Name="MyNode">
    Name="MyNode">
    <Attribute1>Attr</Attribute1>

I have no idea what could be causing this, but maybe it has happened to some of you too. Let me know if you guys found a solution to this problem.

Here's my code:

        using (StreamWriter writer = new StreamWriter(
            File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(MyClass));

            serializer.Serialize(writer, this);
        }

Thanks!开发者_Python百科


You are using the wrong FileMode. OpenOrCreate will not truncate the contents of the file if it already exists, thereby causing your new data to be overlaid on top of the old data. FileMode.Create will do what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜