Changing default culture for windows service runni

2019-08-03 04:53发布

问题:

Our admins unexpectedly migrated a server where my .NET windows service runs (to Windows 2008 ... because of some old apps). It is running under LocalSystem account. The target framework is .NET framework 4 Client Profile.

In my service the method DateTime.Parse now throws invalid format exception.

When I add to OnStart

Thread.CurrentThread.CurrentCulture = new CultureInfo("cs-CZ", false);

it gets better, but still in some methods it fails, probably running in different therads.

How to configure the server or change the program to make all threads be created with proper culture?

回答1:

Starting with Microsoft.NET Framework 4.5 and higher, you can use

var culture = CultureInfo.CreateSpecificCulture("cs-CZ");
CultureInfo.DefaultThreadCurrentCulture = culture;

This is documented here, with the caveat that it might not work for subsequently created threads. A profound solution is included with Microsoft.NET Framework 4.6, read more on it here.