How does a .NET process get the culture information?

.net, c#, datetime

Solution

If a culture has not been set on the thread, `Thread.CurrentThread.CurrentCulture` defaults to the "user default culture" - which it gets from the underlying OS. This is determined by the Formats section in the regional control panel applet.

For a service, it has no control panel settings by default like for a user (the case above) as it runs under the LocalSystem account which will not have a profile, so it uses the system locale from the OS. I'm not sure if this can be set for a service by adjusting the settings in Windows.

There are a few things you could do:

you can explicitly set the `CurrentCulture` of the main thread when the service starts. If you do this, you will need to bear in mind that any new threads that are created in your service will also need to have their `CurrentCulture` set as well, as threads do not inherit their culture from parent threads.

you can set the service to run as a specific user, and set that user's regional settings (the formats section) to be the culture you want to use. When the service starts as that use,it will use that user's regional settings.

since your problem seems to be related to calling `DateTime.ToString()`, make sure you pass the AU culture to the `ToString()` method:

DateTime.ToString(new CultureInfo("en-AU"))

You could add this as an extension method to save you having to do this everywhere:

public static string ToAUString(this DateTime dateTime)
{
    return dateTime.ToString(new CultureInfo("en-AU"));
}

You can then call `DateTime.ToAUString()` to get the correct output.

Problem

I have a Windows service running (C#, .NET 2.0) on Windows Server 2003 R2. In one server the `System.Threading.Thread.CurrentThread.CurrentCulture` is {en-AU} and in the other {en-US}. This has caused a difference when calling ToString() on a DateTime object. I want the culture to be {en-AU}. I checked the "Regional and Language Setting". In both servers, the "Regional Options" tab shows "English (Asutralia)". But in the "Advanced" tab it shows "English (United States)" for one and "English (Australia)" for the other. So this must be causing the difference. Although I want to know why exactly the "Advanced" tab says "the language version of the non-unicode programs you want to use", I thought .NET processes were Unicode and should not be affected by this. How does the .NET runtime determine the culture to use? Any detailed reference would be helpful.

Original source