5

I am trying to serialize an object and the \0 (Null) character is being appended to the generated string. Why?

My code:

 XmlSerializer serializer = new XmlSerializer(typeof(Common.PlanogramSearchOptions));
 MemoryStream memStream = new MemoryStream();
 serializer.Serialize(memStream, searchOptions);

 string xml = Encoding.UTF8.GetString(memStream.GetBuffer()); // appends \0

My work around is replacing the Null character with an empty string

xml.Replace("\0", string.Empty)

Thanks.

alex.davis.dev
  • 411
  • 7
  • 18

1 Answers1

12

MemoryStream.GetBuffer() returns the underlying buffer of the MemoryStream (which is larger than the actual data stored in it). You want MemoryStream.ToArray().

However, I recommend you use a StringWriter instead of MemoryStream, so you can avoid the UTF-8 conversion:

XmlSerializer serializer = new XmlSerializer(typeof(PlanogramSearchOptions));
StringWriter writer = new StringWriter();
serializer.Serialize(writer, searchOptions);
string xml = writer.ToString();

See also: Serialize an object to string

Community
  • 1
  • 1
dtb
  • 213,145
  • 36
  • 401
  • 431
  • Excellent! That worked and thank you for your suggestion... i will implement that across the board. Thank you. – alex.davis.dev Sep 23 '10 at 15:55
  • Thanks. I was using MemoryStream.GetBuffer when I meant ToArray in a different context. Found my way here eventually. :) – Greg May 10 '11 at 15:16