通常可以通过编写以下代码获取当前区域设置:
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
但是这种方式仅能获取在应用程序启动时配置的CultureInfo,如果设置之后更改了,则不会更新。
那么,如何获取在“控制面板” -> “区域和语言设置”中配置的CultureInfo呢?
通常可以通过编写以下代码获取当前区域设置:
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
但是这种方式仅能获取在应用程序启动时配置的CultureInfo,如果设置之后更改了,则不会更新。
那么,如何获取在“控制面板” -> “区域和语言设置”中配置的CultureInfo呢?
正如 @Christian 建议的那样,ClearCachedData 是需要使用的方法。但是根据 MSDN 的说明:
对于现有线程,ClearCachedData 方法不会刷新 Thread.CurrentCulture 属性中的信息。
因此,您需要先调用该函数,然后启动一个新的线程。在这个新线程中,您可以使用 CurrentCulture 来获取文化的新值。
class Program
{
private class State
{
public CultureInfo Result { get; set; }
}
static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture.ClearCachedData();
var thread = new Thread(
s => ((State)s).Result = Thread.CurrentThread.CurrentCulture);
var state = new State();
thread.Start(state);
thread.Join();
var culture = state.Result;
// Do something with the culture
}
请注意,如果你还需要重置CurrentUICulture,则应该单独进行操作。
Thread.CurrentThread.CurrentUICulture.ClearCachedData()
Thread.CurrentThread.CurrentCulture.ClearCachedData()
看起来会导致当下次访问时,文化数据将被重新读取。
[DllImport("kernel32.dll")]
static extern uint GetSystemDefaultLCID();
GetSystemDefaultLCID函数返回LCID。它可以从以下表中映射语言字符串。 Microsoft分配的区域设置ID
我们的WinForms应用程序遇到了这个问题,原因是Visual Studio创建了[MyApp].vshost.exe进程,该进程始终在后台运行,只要Visual Studio打开。
关闭 MyApp -> Properties -> Debug -> "启用Visual Studio托管进程"选项可以解决此问题。
vshost进程主要用于改善调试功能,但如果不想禁用该设置,您可以根据需要结束该进程。
有两个类CultureInfo
和TextInfo
,它们来自命名空间System.Globalization
。这两个类都获取了控制面板中定义的几个Windows区域设置。可用设置列表在文档中。
例如:
string separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
[DllImport("kernel32.dll")]
private static extern int GetUserDefaultLCID();
public static CultureInfo CurrentCultureInRegionalSettings => new CultureInfo(GetUserDefaultLCID());
这段简单的代码对我有效(避免缓存):
// Clear cached data for the current culture
Thread.CurrentThread.CurrentCulture.ClearCachedData();
// In a new thread instance we get current culture.
// This code avoid getting wrong cached cultureinfo objects when user replaces some values in the regional settings without restarting the application
CultureInfo currentCulture = new Thread(() => { }).CurrentCulture;
尝试在SystemInformation
类中查找所需的设置,或者使用System.Management/System.Diagnostics
中的类来查看WMI,您也可以使用LINQ to WMI。