Evgeni Velikov
Evgeni Velikov

Reputation: 382

How can return on current culture who user used in PC

I read csv file and columns is separate with comma. In some cultures the separator is point, and for this reason I decide to change current culture to "en-US", who use comma for separator. But after when I finish with some operation I need return in the culture who user used. But I can't.

How can return current culture who user used?

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

Is continue to be "en-US"

Upvotes: 1

Views: 309

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

Just save and then restore:

var saved = Thread.CurrentThread.CurrentCulture;

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

Another (a bit exotic) possibity is to hide the logic in specially designed class:

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 
}

Upvotes: 2

Dion V.
Dion V.

Reputation: 2120

//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;

Upvotes: 1

Related Questions