Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set CultureInfo.CurrentCulture from an App.Config file?

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?

like image 739
André Pena Avatar asked Feb 01 '12 22:02

André Pena


People also ask

How do you change the current UI culture?

Explicitly Setting the Current UI Culture NET Framework 4.6, you can change the current UI culture by assigning a CultureInfo object that represents the new culture to the CultureInfo. CurrentUICulture property.

How do I declare CultureInfo in VB net?

How to CultureInfo in VB.NET. The CultureInfo class specifies a unique name for each culture, based on RFC 4646. The name is a combination of an ISO 639 two-letter lowercase culture code associated with a language and an ISO 3166 two-letter uppercase subculture code associated with a country or region.

How do I change the current culture in C#?

CurrentCulture = New CultureInfo("th-TH", False) Console. WriteLine("CurrentCulture is now {0}.", CultureInfo.CurrentCulture.Name) ' Display the name of the current UI culture. Console. WriteLine("CurrentUICulture is {0}.", CultureInfo.CurrentUICulture.Name) ' Change the current UI culture to ja-JP.


2 Answers

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.DefaultThreadCurrentUICulture = culture 
like image 109
Adi Lester Avatar answered Oct 13 '22 07:10

Adi Lester


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.DefaultThreadCurrentUICulture = new CultureInfo("pt-BR"); 

I haven't yet found a configuration that matches web.config globalization section unfortunately.

like image 26
Ilya Chernomordik Avatar answered Oct 13 '22 05:10

Ilya Chernomordik