39

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?

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Andre Pena
  • 56,650
  • 48
  • 196
  • 243

3 Answers3

34

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
LeftyX
  • 35,328
  • 21
  • 132
  • 193
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
  • 1
    I think this is the approach you should take if you want to override the system culture in the application. Normally the culture should be automatically picked up from the operating systems settings. Rather than hard coding the culture like this normally I would rely on the client computers having their Region and Language correctly set. – Mick Apr 01 '15 at 06:16
  • 1
    There is a better way in .net from 4.5, see my answer below: https://stackoverflow.com/a/50856078/1671558 – Ilya Chernomordik Jul 08 '18 at 10:46
12

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.

Community
  • 1
  • 1
Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
-4

using System.Threading;

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

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

Md Shahriar
  • 2,072
  • 22
  • 11