How do I set CultureInfo.CurrentCulture from an Ap

2019-01-09 02:58发布

问题:

I need to set my application's culture through an App.Config file, so that "pt-BR" is used automatically for parsing dates without the need to manually inform the culture for each operation.

As far as I know, there's a globalization section that can be defined inside the system.web section in a Web.Config file, but I'm running a console application and I can't figure this out.

Any idea?

回答1:

I don't know a built-in way to set it from App.config, but you could just define a key in your App.config like this

<configuration>
    <appSettings>
        <add key="DefaultCulture" value="pt-BR" />
    </appSettings>
</configuration>

and in your application read that value and set the culture

CultureInfo culture = new CultureInfo(ConfigurationManager.AppSettings["DefaultCulture"]);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;

Also, as @Ilya has mentioned, since .NET 4.5 you can set the default culture once, rather than per-thread:

CultureInfo.DefaultThreadCurrentCulture = culture
CultureInfo.DefaultThreadUICurrentCulture = culture


回答2:

Starting form .Net 4.5 it's possible to set the default thread culture so there is no need to fix it per thread:

CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("pt-BR");
CultureInfo.DefaultThreadUICurrentCulture = new CultureInfo("pt-BR");

Have not yet found any way that matches web.config globalization section unfortunately.



回答3:

using System.Threading;

Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("bn-BD");

//For Bangladesh. I use this line on every page form load event