.net 如何从 App.Config 文件设置 CultureInfo.CurrentCulture?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9104084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 16:13:09  来源:igfitidea点击:

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

.netconfigurationlocalizationapp-configglobalization

提问by André Pena

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.

我需要通过 App.Config 文件设置我的应用程序的文化,以便“pt-BR”自动用于解析日期,而无需为每个操作手动通知文化。

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

据我所知,globalization可以system.web在 Web.Config 文件的部分内定义一个部分,但我正在运行一个控制台应用程序,我无法弄清楚这一点。

Any idea?

任何的想法?

采纳答案by Adi Lester

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

我不知道从 App.config 设置它的内置方法,但是您可以像这样在 App.config 中定义一个键

<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:

此外,正如@Ilya 所提到的,从 .NET 4.5 开始,您可以设置默认文化一次,而不是每个线程:

CultureInfo.DefaultThreadCurrentCulture = culture
CultureInfo.DefaultThreadCurrentUICulture = culture

回答by Ilya Chernomordik

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

从 .Net 4.5 开始,可以设置默认线程文化,因此无需为每个线程修复它:

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

I haven't yet found a configuration that matches web.configglobalizationsection unfortunately.

web.configglobalization不幸的是,我还没有找到与部分匹配的配置。

回答by Md Shahriar

using System.Threading;

使用 System.Threading;

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

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

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

//对于孟加拉国。我在每个页面表单加载事件上都使用这一行