Does XML serialization create random strings at the end? FROM#

When the class is serialized and the file is saved, an error sometimes occurs when 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 serialization of the class I is as follows:

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

I can’t understand why this is happening. Here is 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!

+6
source share
1 answer

The additional output is likely to remain the same version of the output file (with the same name).

You can solve the problem by changing FileMode only from OpenOrCreate to Create . Thus, 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); } 

On the sidelines: it is usually preferable that exceptions allow you to exclude a call bubble until you can do something meaningful with them. Just silently swallowing the exception and instead returning a status flag that can never be checked, hides the actual problem, can lead to further problems later and makes it difficult to analyze the problem.

+8
source

All Articles