How to get current regional settings in C#?

▼魔方 西西 提交于 2019-11-27 04:46:54
Darin Dimitrov

As @Christian proposed ClearCachedData is the method to use. But according to MSDN:

The ClearCachedData method does not refresh the information in the Thread.CurrentCulture property for existing threads

So you will need to first call the function and then start a new thread. In this new thread you can use the CurrentCulture to obtain the fresh values of the culture.

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
    }

}

Note, that if you also need to reset CurrentUICulture, you should do it separately

Thread.CurrentThread.CurrentUICulture.ClearCachedData()

Thread.CurrentThread.CurrentCulture.ClearCachedData() looks like it will cause the culture data to be re-read when it is next accessed.

You can use Win32 API function GetSystemDefaultLCID. The signiture is as follow:

[DllImport("kernel32.dll")]
static extern uint GetSystemDefaultLCID();

GetSystemDefaultLCID function returns the LCID. It can map language string from the folowing table. Locale IDs Assigned by Microsoft

We ran into to this issue with our WinForms app and it was due to Visual Studio creating the [MyApp].vshost.exe process that is always running in the background whenever Visual Studio is open.

Turning off the MyApp -> Properties -> Debug -> "Enable Visual Studio hosting process" setting fixed this for us.

The vshost process is mainly used to improve debugging, but if you don't want disable the setting, you can kill the process as needed.

Nicolas

There are the classes CultureInfo and TextInfo from the namespace System.Globalization. Both classes get several windows regional settings defined in the control panels. The list of available settings is in the documentation.

For example:

string separator = CultureInfo.CurrentCulture.TextInfo.ListSeparator;

is getting the list separator for the program which is running.

[DllImport("kernel32.dll")]
private static extern int GetUserDefaultLCID();

public static CultureInfo CurrentCultureInRegionalSettings => new CultureInfo(GetUserDefaultLCID());

Try to find settings you want in SystemInformation class or look into WMI using the classes in System.Management/System.Diagnostics, you can use LINQ to WMI too

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!