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

3

40

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?

Astrakhan answered 1/2, 2012 at 22:8 Comment(0)
B
35

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
Bouffe answered 1/2, 2012 at 22:48 Comment(2)
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.Benne
There is a better way in .net from 4.5, see my answer below: https://mcmap.net/q/398174/-how-do-i-set-cultureinfo-currentculture-from-an-app-config-fileQktp
Q
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.

Qktp answered 14/6, 2018 at 11:6 Comment(0)
S
-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

Stumpage answered 19/3, 2017 at 22:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.