11

I'm having an issue with some byte conversions and a few of my calculations in one of my applications. I was able to contribute it to the person running it having an Italian Culture setting in windows. So my question is: What is the best way to for "en-US" on any computer running my application. I have a code sample below, but I am unsure if any thread I use will inhert it.

[STAThread]
static void Main()
{
    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

    ...
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • This: "I'm having an issue with some byte conversions" should not have anything to do with the Culture settings. The problem is in the conversions, not in the fact that a non-en-US culture is selected. – Sam Harwell Aug 15 '09 at 22:55

2 Answers2

15

The problem you describe is the reason InvariantCulture exists. Rather than change your application's culture, you should do your behind-the scenes data manipulation/persistence with the invariant culture and then let the user's culture determine how values are rendered.

dahlbyk
  • 75,175
  • 8
  • 100
  • 122
12

Your code will set the culture of the current thread, but any new threads that are created will not have this culture 'inherited'. You have to set the culture you require yourself. (I believe that any new threads will be created with the installed Windows culture, but I'm prepared to be proved wrong on that.)

This is answered in this post: Is there a way of setting culture for a whole application? All current threads and new threads?

Personally, I find this behaviour annoying, but that's the way it is.

Community
  • 1
  • 1
Andy
  • 5,188
  • 10
  • 42
  • 59
  • 1
    Actually it makes good sense. Think about ASP.NET where multiple users accessing a site can have separate cultures active at any given point in time. You need to have a baseline to start from if there's fallback when a culture can't be matched. – Rick Strahl Mar 10 '15 at 01:38
  • @Rick: That's a fair point. I have no experience in ASP.NET so it's not something I have considered before. – Andy Mar 10 '15 at 21:13
  • Incorrect about ASP.NET. It would take culture info from the server where the website is running, not from user's machine (how could it have access to that?). The website might take into consideration the HTTP header Accept-Language though, but this is not guaranteed (depends if it's been coded for that and if it offers the requested language) – Alex Sanséau Mar 20 '18 at 12:01
  • Under ASP.NET you can customize the culture on a per-request bases - that's how culture was designed (as was identity). How that occurs is developer discretion (e.g. from what the user agent tells the server). Under ASP.NET Core, the concept is the same (See `RequestLocalizationOptions`). – Mark Lopez Mar 03 '22 at 15:26