Monday, July 22, 2013

CSharp C# XDocument example to change an App.Config AppSettings key attribute value

CSharp C# XDocument example  to change an App.Config  AppSettings key attribute value

Overview:
This example shows how to work with an xml content file with XDocument, as opposed to an XMLDocument, and other related objects, to use System.Linq to avoid cycling through IEnumerable objects.  This is a File IO vs. an in memory example such as here.

Goal of this example:
In our App.Config  file we have the value “IE”, as follows:
 <add key="Browser" value="IE" />
- and we will change that to ”Chrome”:
  <add key="Browser" value="Chrome" />

App.Config file before the change:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
  </configSections>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
    </root>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="log.txt" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="DEBUG" />
        <param name="LevelMax" value="FATAL" />
      </filter>
    </appender>
  </log4net>
  <appSettings>
    <!-- Choices: IE, Mozilla, Chrome, Safari -->
    <add key="Browser" value="IE" />
    <add key="TargetiURL" value="https://serengeti.int.qaintegration.thomsonreuters.com/" />
    <add key="CompanyName" value="MyTargetCompany" />
  </appSettings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  </startup>
</configuration>


App.Config file after the change:


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
  </configSections>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
    </root>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="log.txt" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="DEBUG" />
        <param name="LevelMax" value="FATAL" />
      </filter>
    </appender>
  </log4net>
  <appSettings>
    <!-- Choices: IE, Mozilla, Chrome, Safari -->
    <add key="Browser" value="Chrome" />
    <add key="TargetiURL" value="https://serengeti.int.qaintegration.thomsonreuters.com/" />
    <add key="CompanyName" value="MyTargetCompany" />
  </appSettings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  </startup>
</configuration>


Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleStuff
{
    class Program
    {
        static void Main(string[] args)
        {
            string targetFile = @"C:\dump\BVT.dll.config";
            XDocument fileNow = XDocument.Load(targetFile);

            //This will be the object we edit:
            XAttribute targetAddKeyForBrowser;

            //Show the initial attribute value - "IE"
            {
                IEnumerable<XAttribute> listOfAttributes =
                    from targetAddKey in fileNow.Descendants(@"appSettings").Descendants("add")
                    where (string) targetAddKey.Attribute("key") == "Browser"
                    select targetAddKey.Attribute("value");

                targetAddKeyForBrowser = listOfAttributes.First();
                Console.WriteLine("targetAddKey = {0}", targetAddKeyForBrowser);
            }

            targetAddKeyForBrowser.Value = "Chrome";

            //Show the modified attribute value - "Chrome"
            {
                IEnumerable<XAttribute> listOfAttributes =
                  from targetAddKey in fileNow.Descendants(@"appSettings").Descendants("add")
                  where (string)targetAddKey.Attribute("key") == "Browser"
                  select targetAddKey.Attribute("value");

                targetAddKeyForBrowser = listOfAttributes.First();
                Console.WriteLine("targetAddKey = {0}", targetAddKeyForBrowser);
            }

            //Save the file with the above change:
            fileNow.Save(targetFile);

            Console.WriteLine();
            Console.WriteLine("press enter to finish");
            Console.ReadLine();

        }
    }
}


Output from the above console program:

targetAddKey = value="IE"
targetAddKey = value="Chrome"

press enter to finish


1 comment: