Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

cultureinfo - How to get current regional settings in C#?

Normally you can get it by writing something like

CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;

But this way you can only get CultureInfo which was configured at the moment application was launched and will not update if the setting have been changed afterwards.

So, how to get CultureInfo currently configured in Control Panel -> Regional and Language Settings?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...