【发布时间】:2010-12-05 06:31:34
【问题描述】:
通常你可以通过写类似的东西来获得它
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
但是这样你只能获取应用程序启动时配置的 CultureInfo,如果之后更改设置,则不会更新。
那么,如何获取当前在控制面板->区域和语言设置中配置的CultureInfo?
【问题讨论】:
标签: c# cultureinfo
通常你可以通过写类似的东西来获得它
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
但是这样你只能获取应用程序启动时配置的 CultureInfo,如果之后更改设置,则不会更新。
那么,如何获取当前在控制面板->区域和语言设置中配置的CultureInfo?
【问题讨论】:
标签: c# 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()
【讨论】:
State 是我在 Program 类中定义的私有类,但您可以尝试将其外部化到自己的文件中并将其公开。另外State 可能不是一个很好的名字,所以您可以尝试将其重命名为更有意义的名称。
Thread.CurrentThread.CurrentCulture.ClearCachedData() 看起来会导致文化数据在下次访问时被重新读取。
【讨论】:
您可以使用 Win32 API 函数 GetSystemDefaultLCID。 签名如下:
[DllImport("kernel32.dll")]
static extern uint GetSystemDefaultLCID();
GetSystemDefaultLCID 函数返回 LCID。它可以从下表映射语言字符串。 Locale IDs Assigned by Microsoft
【讨论】:
我们的 WinForms 应用程序遇到了这个问题,这是由于 Visual Studio 创建了 [MyApp].vshost.exe 进程,该进程始终在 Visual Studio 打开时在后台运行。
关闭 MyApp -> 属性 -> 调试 -> “启用 Visual Studio 托管进程”设置为我们解决了这个问题。
vshost进程主要用于改善调试,但如果不想禁用该设置,可以根据需要终止该进程。
【讨论】:
有来自命名空间System.Globalization 的类CultureInfo 和TextInfo。这两个类都获得了在控制面板中定义的几个窗口区域设置。可用设置列表在文档中。
例如:
string separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
正在获取正在运行的程序的列表分隔符。
【讨论】:
[DllImport("kernel32.dll")]
private static extern int GetUserDefaultLCID();
public static CultureInfo CurrentCultureInRegionalSettings => new CultureInfo(GetUserDefaultLCID());
【讨论】:
尝试在SystemInformation中找到你想要的设置
类或使用System.Management/System.Diagnostics 中的类查看WMI,您也可以使用LINQ to WMI
【讨论】:
这个简单的代码对我有用(避免缓存):
// 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;
【讨论】: