1

I'm dealing with some crashes in our mobile apps, and I'm trying to narrow the problem down as much as possible. In the process I've found some rather strange behavior.

This is using Xamarin on Android.

I've isolated it down to this code (simplified for the sake of keeping it short):

// Using a very simple class:
public class A
{
}

// Then serializing it using XmlSerializer:
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(A));
using (MemoryStream memoryStream = new MemoryStream())
{
    serializer.Serialize(memoryStream, new A());

    var array = memoryStream.ToArray();
    var firstChar = System.Text.Encoding.UTF8.GetString(array,
        0, array.Length)[0];
    // look at firstChar in the watch window
}

firstChar is what seems to be an empty character, but putting (int)firstChar in the watch window produces the result 65279.

I tried the exact same code on desktop PC using a .NET 4.6.1 Console Application and the first character comes out as <, the opening bracket in XML.

I should point out that after the weird first character, the remainder of the XML is correct - it just has this one additional letter prefixed.

Why does Android have this behavior? Am I safe to strip out the first character so that my Android app behaves the same as my PC app so that I can further isolate differences causing crashes?

Victor Chelaru
  • 4,491
  • 3
  • 35
  • 49
  • 3
    65279 is the Byte Order Mark - see https://stackoverflow.com/questions/969941/xmltextwriter-serialization-problem/970023 – Jason Apr 20 '18 at 16:14

1 Answers1

4

Quote from here:

The reason for your result is because you are calling Encoding.UTF8.GetString, which is intended to convert a sequence of bytes in UTF8 encoding into a C# string.

65279 is the prepend of UTF-8 BOM.

Like @Jason has said, here, you can this:

using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
    var serializer = new XmlSerializer(typeof(A));
    Encoding utf8EncodingWithNoByteOrderMark = new UTF8Encoding(false);
    XmlTextWriter xtw = new XmlTextWriter(memoryStream, utf8EncodingWithNoByteOrderMark);
    serializer.Serialize(xtw, new A());
    string xml = Encoding.UTF8.GetString(memoryStream.ToArray());
    Log.Error("lv", xml[0]+"");
}

to make your Android app behaves the same as your PC app.

Robbit
  • 4,300
  • 1
  • 13
  • 29