0

I'm using serialization to a string as follows.

public static string Stringify(this Process self)
{
  XmlSerializer serializer = new XmlSerializer(typeof(Process));
  using (StringWriter writer = new StringWriter())
  {
    serializer.Serialize(writer, self,);
    return writer.ToString();
  }
}

Then, I deserialize using this code. Please note that it's not an actual stringification from above that's used. In our business logic, it makes more sense to serialize a path, hence reading in from said path and creating an object based on the read data.

public static Process Processify(this string self)
{
  XmlSerializer serializer = new XmlSerializer(typeof(Process));
  using (XmlReader reader = XmlReader.Create(self))
    return serializer.Deserialize(reader) as Process;
}

}

This works as supposed to except for a small issue with encoding. The string XML that's produced, contains the addition encoding="utf-16" as an attribute on the base tag (the one that's about XML version, not the actual data).

When I read in, I get an exception because of mismatching encodings. As far I could see, there's no way to specify the encoding for serialization nor deserialization in any of the objects I'm using.

How can I do that?

For now, I'm using a very brute work-around by simply cutting of the excessive junk like so. It's Q&D and I want to remove it.

public static string Stringify(this Process self)
{
  XmlSerializer serializer = new XmlSerializer(typeof(Process));
  using (StringWriter writer = new StringWriter())
  {
    serializer.Serialize(writer, self,);
    return writer.ToString().Replace(" encoding=\"utf-16\"", "");
  }
}
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • See this existing answer: http://stackoverflow.com/a/955698/67392 You can override the encoding that `string`/`StringWriter` assume. – Richard Oct 05 '15 at 08:00
  • Another option could be to use `DataContractSerializer` and `OnSerializing` attribute http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/06/wcf-extensibility-serialization-callbacks.aspx – Milen Oct 05 '15 at 08:07

0 Answers0