如何回归用户在PC中使用的当前文化

时间:2015-11-30 12:45:04

标签: c# wpf cultureinfo culture

我读了csv文件,列与逗号分开。在某些文化中,分隔符是点,因此我决定将当前文化更改为" en-US",他们使用逗号作为分隔符。但是当我完成某些操作后,我需要返回用户使用的文化。但我不能。

如何返回用户使用的当前文化?

Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
// do something 
CultureInfo ci = CultureInfo.CurrentCulture;
var a = ci.DisplayName;

继续是" en-US"

2 个答案:

答案 0 :(得分:2)

只需保存,然后恢复

var saved = Thread.CurrentThread.CurrentCulture;

try {
  Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
  // do something 
finally {
  Thread.CurrentThread.CurrentCulture = saved;
}

另一个(有点异国情调)可能性是在特别设计的类中隐藏逻辑:

public sealed class CurrentCulture: IDisposable {
  private CultureInfo m_Saved;

  public CurrentCulture(CultureInfo info) {
    //TODO: validate info
    m_Saved = Thread.CurrentThread.CurrentCulture;
    Thread.CurrentThread.CurrentCulture = info;
  }

  public CurrentCulture(String name) :
    this(new CultureInfo(name)) {
  }

  public void Dispose() {
    if (m_Saved != null) {
      Thread.CurrentThread.CurrentCulture = m_Saved;
      m_Saved = null;
    }
  }
}

...

using (var c = new CurrentCulture("en-US")) {
  // do something 
}

答案 1 :(得分:1)

//Save your current culture;
var myCurrentCulture = Thread.CurrentThread.CurrentCulture;

//Adjust the culture
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");

//Set it back
Thread.CurrentThread.CurrentCulture = myCurrentCulture;

CultureInfo ci = CultureInfo.CurrentCulture;
var a = ci.DisplayName;