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!
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 OpenOrCreate
to 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With