简体   繁体   中英

Get user culture, not thread culture

When my application starts, it sets its own culture to CultureInfo.InvariantCulture but in some places, I want to use localized number formatting according to what the user has set in Windows. How can I do this? System.Globalization.CultureInfo.CurrentCulture only returns the thread's culture which is no longer the user's default.

I'm hoping for a more elegant way than storing the thread's default culture before changing it or creating a new thread just to read the culture out of it.

Maybe there's a built-in .Net wrapper for the Windows function GetUserDefaultLocaleName ?

System.Globalization.CultureInfo has an internal property named UserDefaultCulture which is the equivalence of the Win32 GetUserDefaultLCID() as commented in .NET Source code:

 // // This is the equivalence of the Win32 GetUserDefaultLCID() // internal static CultureInfo UserDefaultCulture

So you can use it to get user default culture this way:

var property = typeof(System.Globalization.CultureInfo).GetProperty("UserDefaultCulture",
    System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
var culture = (System.Globalization.CultureInfo)property.GetValue(null);

Also as another option, you can create a new thread and use its CurrentCulture property:

var culture = new System.Threading.Thread(() => { }).CurrentCulture;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM