简体   繁体   English

在C#中以编程方式更改Windows文化

[英]Changing windows culture programmatically in C#

I want to change the windows culture settings programmatically since when using my program I need to parse the dot "." 我想以编程方式更改Windows区域性设置,因为在使用程序时,我需要解析点“”。 as the decimal number and windows has by default set the ",". 作为十进制数字,Windows默认情况下将其设置为“,”。 So I'm looking for this. 所以我正在寻找这个。

I already tried by changing the current app culture but when parsing data from db it still gets in trouble because it uses windows configuration. 我已经尝试过通过更改当前应用的区域性来进行尝试,但是当从db解析数据时,它仍然会遇到麻烦,因为它使用Windows配置。

I'll emphasize, do it better. 我会强调,做得更好。

This can be pretty easily solved, and a quick example: 这很容易解决,下面是一个简单的示例:

public static decimal GetInvariantDecimal(string internationDecimalString)
{
    var looksUnAmerican = Regex.IsMatch(internationDecimalString, @"(\d+,\d{2}\b)|(\d+\.\d+,\d{0,2})|(\d+\.\d{3})");
    Console.WriteLine(looksUnAmerican);
    return looksUnAmerican ? 
        Decimal.Parse(internationDecimalString, NumberStyles.Currency, CultureInfo.GetCultureInfo("tr-TR")) :
        Decimal.Parse(internationDecimalString,  CultureInfo.InvariantCulture);
}

public static void Main()
{
    var american = "123.55";
    var international = "234,55";       

    Console.WriteLine(GetInvariantDecimal(american));
    Console.WriteLine(GetInvariantDecimal(international));
}

It will give you a standard decimal for the correct environment, and you would use this every time you work with the string from the database. 它将为您提供正确环境的标准十进制数,并且每次使用数据库中的字符串时都将使用该十进制数。 (of course, it doesn't currently handle something like "1,234.01"... (当然,它目前不处理“ 1,234.01”之类的问题...

But output: 但是输出:

123.55
234.55

And one more bit, changing the users machines culture will likely cause all sorts of bugs in who knows what... 还有一点是,改变用户的机器文化可能​​会导致各种错误,这些错误会导致谁知道什么……

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM