Ben_G
Ben_G

Reputation: 826

how do I read from a file and update it in c#

I need to make changes to a web.config, so I need to read up until the point where I need to make the change, make the change and then write my update out to the file.

So let's say the file contained:

<add key="Version_PSM" value="2.2.0"/>
<add key="Version_MLF" value="2.0.3"/>

And I needed to update the version pf Version_PSM to "2.1". What's the best way to do this? I've tried opening a FileStream and then creating a StreamReader and a StreamWriter using it, but that doesn't work. As I read lines from the file looking for the key I want to update the Writer stays in position at the beginning of the file, so when I write it doesn't overwrite what I've just read - it writes it to the top of the file. So first I tried something like this:

// Repeat in a loop until I find what I'm looking for...
string readLine = sr.ReadLine();
sw.WriteLine(readline);

which advances the position of the writer, but duplicates what's in the file. I need to position the writer to overwrite the text that I want to update and leave everything else as-is.

So I tried just:

readLine = sr.ReadLine();
sw.WriteLine();

but that just writes blanks to the file.

There's gotta be an easy answer here that I'm just missing!

Upvotes: 2

Views: 434

Answers (1)

Fruchtzwerg
Fruchtzwerg

Reputation: 11389

Since you need to change values during installation, you could use LINQ to XML to solve your problem (using System.Xml.Linq;). Typically a web.config file looks like

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <appSettings>
    <add key="Version_PSM" value="2.2.0" />
    <add key="Version_MLF" value="2.0.3" />
  </appSettings>
</configuration>

You are able to access and edit nodes based on their names and attributes. After you changed some values you can save the changes. In the following example we are changing the value of the Version_PSM setting. As you can see dealing with the namespace correctly is a bit trick in this case.

//Specify path
string webConfigFile = @"\web.config";

//Load the document and get the default configuration namespace
XDocument doc = XDocument.Load(webConfigFile);
XNamespace netConfigNamespace = doc.Root.GetDefaultNamespace();

//Get and edit the settings
IEnumerable<XElement> settings = doc.Descendants(netConfigNamespace + "appSettings").Elements();
XElement versionPsmNode = settings.FirstOrDefault(a => a.Attribute("key").Value == "Version_PSM");
versionPsmNode?.Attribute("value").SetValue("New value");

//Save the document with the correct namespace
doc.Root.Name = netConfigNamespace + doc.Root.Name.LocalName;
doc.Save(webConfigFile);

Upvotes: 2

Related Questions