System.FormatException: Input string was not in a correct format. The exception I see again and again because I’m running an English Windows 7 with Slovak regional settings and some developers just can’t imagine there are regions in the world where the decimal separator is not a period (.) but a comma (,) or where they use more than 12 hours a day. It’s unfortunate for them because many more people live outside the USA so reach of their application is far less than it could be.
Today I want to build a demonstration utilizing a Ribbon bar in my Silverlight application and I found one. A sample was attached but it crashed immediately after start with the aforementioned exception. The Ribbon control stores some default brushes in an XML file and parses on its own with code like this:
string xStr = pointAsString.Substring(0, pointAsString.IndexOf(","));
string yStr = pointAsString.Substring(pointAsString.IndexOf(",") + 1);
return new Point(double.Parse(xStr), double.Parse(yStr));
If we take a look at a fragment of the XML:
<LinearGradientBrush Name="GroupedButtonSemiHighlight" StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#FFFEF7" Offset="0.0" />
<GradientStop Color="#FFF7DF" Offset="0.5" />
<GradientStop Color="#FFEEBE" Offset="0.6" />
<GradientStop Color="#FFF6DD" Offset="1.0" />
</LinearGradientBrush>
we see that it cannot succeed on any client configuration which does not use a point as decimal separator because the double.Parse method without providing an IFormatProvider would parse the string using the current regional settings.
If you write code that parses numbers from a content not edited or viewable directly by users and don’t want to take regional settings into account, always use the Invariant Culture as your IFormatProvider.
So I fixed the code:
string xStr = pointAsString.Substring(0, pointAsString.IndexOf(","));
string yStr = pointAsString.Substring(pointAsString.IndexOf(",") + 1);
return new Point(double.Parse(xStr, CultureInfo.InvariantCulture), double.Parse(yStr, CultureInfo.InvariantCulture));
More detailed information on internationalization, globalization and localization issues can be found on the Globalization Step By Step Microsoft site.
[digg]