When converting for instance a decimal
to a string
, you use the CultureInfo.InvariantCulture
and pass it as an IFormatProvider
Try to cast your value
to IFormattable
:
foreach (var property in typeof(Order).GetProperties(BindingFlags.Public | BindingFlags.Instance).
Where(c => ValidTypes.Contains(c.PropertyType)))
{
var value = property.GetValue(order, null);
if (value != null)
{
var formattable = value as IFormattable;
writer.WriteElementString(property.Name,
formattable == null ? value.ToString() : formattable.ToString(null, CultureInfo.InvariantCulture));
}
}
Handy extension method of Peter's solution (modified to test also for IConvertible).
public static string ToInvariantString(this object obj)
{
return obj is IConvertible ? ((IConvertible)obj).ToString(CultureInfo.InvariantCulture)
: obj is IFormattable ? ((IFormattable)obj).ToString(null, CultureInfo.InvariantCulture)
: obj.ToString();
}
Try one of these:
string valueString = XmlConvert.ToString(value);
string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
XmlConvert.ToString() is made for XML, so it will keep things closer to the XML spec, such as using "true" instead of "True". However, it is also more brittle than Convert.ToString(). For example, this will throw an exception because of the UTC time:
XmlConvert.ToString(DateTime.UtcNow)
but this works:
XmlConvert.ToString(DateTime.UtcNow, "o")