Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Serialization produces random strings at the end? C# [duplicate]

When seralizing a class and saving to a file, sometimes an error occurs where the serialized output looks like this:

<?xml version="1.0"?>
<Template xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Route>Some Route</Route>
    <TradePack>Something Here</TradePack>
    <Transport />
</Template>te> ------> Notice this extra string?

The class I'm serializing looks like this:

[Serializable]
public class Template
{
    public string Route = string.Empty;
    public string TradePack = string.Empty;
    public string Transport = string.Empty;

    public Template()
    {

    }
}

I can't seem to figure out why this is happening. Here's my serializer class:

    public static bool Save(object obj, string path)
    {
        try
        {
            XmlSerializer writer = new XmlSerializer(obj.GetType());

            using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                writer.Serialize(stream, obj);
            }

            return true;
        }
        catch { }
        return false;
    }

Thanks!

like image 876
J. Doe Avatar asked Jul 07 '16 11:07

J. Doe


1 Answers

The additional output is likely a leftover from a previous version of the output file (having the same name).

You can solve the problem by changing the FileMode from OpenOrCreateto Create only. That way the output file is truncated if it already exists.

An even simpler method would be to use File.Create(path):

XmlSerializer writer = new XmlSerializer(obj.GetType());
using (var stream = File.Create(path))
{
    writer.Serialize(stream, obj);
}

As an aside: It is usually preferable to just let exceptions bubble up the call stack until you can do something meaningful with them. Just silently swallowing the exception and instead returning a status flag which might never be checked hides the actual problem, might lead to further issues later on and makes a problem analysis unnecessarily difficult.

like image 70
Dirk Vollmar Avatar answered Oct 10 '22 06:10

Dirk Vollmar