Rainbolt
Rainbolt

Reputation: 3660

Change Culture in Web.Config Programmatically

My configuration application collects the culture from the user. It is captured after the user makes a selection.

CultureInfo culture = new CultureInfo(selectedCulture);

Now, I need to update the Web.config of the main application. Currently, it defaults to en-us:

<system.web>
    ...
    <globalization culture="en-us" responseEncoding="utf-8" />
    ...
</system.web>

Here is what I have managed so far, with the part I am failing to figure out highlighted with a TODO.

XmlDocument config = new XmlDocument();
config.Load("C:\\inetpub\\wwwroot\\MyProject\\web.config");
// TODO - Modify the globalization culture
config.Save("C:\\inetpub\\wwwroot\\MyProject\\web.config");

I see methods for grabbing elements by ID, but my globalization doesn't have an ID. When i tried to give it an ID, I got The "id" attribute is not allowed. What method will manipulate the globalization element in a way that allows me to change the culture? Do I need to use a different structure to load the document?

Upvotes: 0

Views: 1335

Answers (2)

qjuanp
qjuanp

Reputation: 2816

You need to consider that: if you modify your web.config ASP.NET will restart your application.

Instead of that, you can set your globalization in web.config like:

<system.web> ... <globalization culture="auto" responseEncoding="utf-8" /> ... </system.web>

Then, you can use, as @luke-mcgregor said, Thread.CurrentCulture to retrieve the user's culture

Upvotes: 0

John Koerner
John Koerner

Reputation: 38077

You can use Xpath to find the element and then update the data:

XmlDocument config = new XmlDocument();
config.Load("C:\\inetpub\\wwwroot\\MyProject\\web.config");

var node = config.SelectNodes("system.web/globalization")[0];
node.Attributes["culture"].Value = "new value";

config.Save("C:\\inetpub\\wwwroot\\MyProject\\web.config");

Upvotes: 2

Related Questions