Change value in existing Web.config file

  • Thread starter Thread starter Frankie
  • Start date Start date
F

Frankie

I'm writing a small utility app (C# Windows forms) used to create new
ASP.NET Web sites. This utility needs to be able to change existing values
in an existing Web.config. Please note: I do NOT want to make this change
from any currently running Web application. Rather, I plan to have a
"base/standard Web.config" that is copied then updated by the utility app
for each new Web site.

I'm hoping there is some straight-forward way to do this. I have Googled
this and found lots of overly-complicated stuff (like rewriting the entire
file, doing stuff with XSLT,etc). I'm relatively new to working with XML
files, and that other stuff just seems overkill.

The following is an abbreviated version of the Web.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="MyKey" value="MyValue" />
</appSettings>
<!-- other stuff here -->
</configuration>


What I want to be able to do is to programmatically change the entry in
<appSettings>...
FROM
<add key="MyKey" value="MyValue" />
TO
<add key="MyKey" value="YourValue" />


Thanks!
 
Replace the values in your base web.config file with tokens (e.g.
[SOME_VALUE]).

From your utility, read the file into a string. Replace the tokens with
whatever values you need, and write it back out again.
 
Hi,

What about reading the file, look for the line with the key that you want
and replace the value with your new value.
IMO I think it would be better if you treat it as XML. It's not so complex
at all.

if not try to use Regex, cause you may want to change the vale for the same
key more than once.


cheers,
 
: [...]
: The following is an abbreviated version of the Web.config file:
:
: <?xml version="1.0" encoding="utf-8" ?>
: <configuration>
: <appSettings>
: <add key="MyKey" value="MyValue" />
: </appSettings>
: <!-- other stuff here -->
: </configuration>
:
: What I want to be able to do is to programmatically change the entry
: in <appSettings>...
: FROM
: <add key="MyKey" value="MyValue" />
: TO
: <add key="MyKey" value="YourValue" />

Here's one way to do it:

static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load("Web.config");

XmlNode node = doc.SelectSingleNode("/configuration/appSettings/add");
if (node is XmlElement)
{
XmlElement add = (XmlElement) node;
add.SetAttribute("value", "Your Value");
}

XmlTextWriter w = new XmlTextWriter(Console.Out);
w.Formatting = Formatting.Indented;
w.Indentation = 3;

doc.WriteTo(w);
}

Hope this helps,
Greg
 
Back
Top