Reputation: 99
i use this code for serialize needed objects (use DataContractSerialier)
try { using (var stream = File.OpenWrite(filePath)) { var dcs = new DataContractSerializer(typeof(T)); dcs.WriteObject(stream, obj); } } catch (Exception ex) { throw new Exception("Error during write object to xml file", ex); }
i don't understand, but sometimes this method append to end of xml-file some additional symbols. for example :"eInfo>" ( when i deleted 'eInfo>' deserialization works good). i found this when do high load testing (call this method 12000 times without stoping). maybe i can checking that file was saved correctly (try to deserialize saved file), but i think that it bad idea, because we need to run deserialize procees any time when save xml-file.
Upvotes: 2
Views: 184
Reputation: 1063964
That is because File.OpenWrite
does not truncate the existing data. You are over-writing a file with less data. The garbage at the end is whatever was left over from the original file. I suggest you use File.Create
(which is actually create or overwrite-with-truncate), or explicitly specify truncate, or call .SetLength(0)
before writing.
Upvotes: 3