Converting String to Single in C#

Some time ago, I needed to get Flash Movie sizes inside of my C# code. I googled and I found some great examples of how I can do it. It was Mike Swanson’s example project called FlashTools. I downloaded it and stated to use. While I was using this code I found a little bug that was occured depending of regional settings in the system. An error occured when FlashTools library tryed to convert String to Single. When I used English locale everything was going OK but when I changed the locale I got “Input string was not in a correct format”. A fix was very simple, I just passed the InvariantCulture as the second parameter of Convert.ToSingle method.

A code snippet that causes an error:

// private Single frameRate = 0.0F;
string sFrameRate = String.Format("{0}.{1}", frameRateMajor, frameRateMinor);
this.frameRate = Convert.ToSingle(sFrameRate);

A workaround:

// private Single frameRate = 0.0F;
string sFrameRate = String.Format("{0}.{1}", frameRateMajor, frameRateMinor);
this.frameRate = Convert.ToSingle(sFrameRate, 
  System.Globalization.CultureInfo.InvariantCulture);

Using the System.Globalization.CultureInfo.InvariantCulture the Convert.ToSingle method converts String to Single using the specified culture-specific formatting information.

Links

Example C# Code for Reading Flash (SWF) Files