如何在C#中获取当前的区域设置?
通常你可以写一些像这样的东西
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()
看起来会导致文化数据在下次访问时被重新读取。
您可以使用Win32 API函数GetSystemDefaultLCID。 签名如下:
[DllImport("kernel32.dll")] static extern uint GetSystemDefaultLCID();
GetSystemDefaultLCID函数返回LCID。 它可以映射下表中的语言字符串。 由Microsoft分配的区域设置ID
我们使用WinForms应用程序遇到了这个问题,这是因为Visual Studio创建的[MyApp] .vshost.exe进程在Visual Studio打开时始终在后台运行。
关闭MyApp – >属性 – >调试 – >“启用Visual Studio主机进程”设置为我们解决了这个问题。
vshost进程主要用于改进调试,但如果您不想禁用该设置,则可以根据需要终止该进程。
命名空间System.Globalization
有类CultureInfo
和TextInfo
。 这两个类都获得了控制面板中定义的几个窗口区域设置。 可用设置列表位于文档中。
例如:
string separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
正在运行正在运行的程序的列表分隔符。
尝试在SystemInformation
类中查找所需的设置或使用System.Management/System.Diagnostics
的类查看WMI,您也可以使用LINQ to WMI
[DllImport("kernel32.dll")] private static extern int GetUserDefaultLCID(); public static CultureInfo CurrentCultureInRegionalSettings => new CultureInfo(GetUserDefaultLCID());