1

I have an app.config file.

I want to retrive and edit an attribute:

<appSettings>
    <add key="ProcessorInstances" value="2" />
</appSettings>

I am using this query:

var list5 = from appNode in doc2.Descendants("appSettings").Elements() 
            where appNode.Attribute("key").Value == "ProcessorInstances" 
            select appNode;
var element5 = list5.FirstOrDefault();
string five = element5.Attribute("value").Value; 

But now I am facing elements like:

<app>
    <file value="../../../logs/Intel.Service.log" />
</app>

and:

<baseAddresses>
    <add baseAddress="http://Machinename:portnumber/servicename/" />
</baseAddresses>

These elements don't have any key attribute.

How can I write a LINQ query to edit them?

Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
user1410658
  • 551
  • 3
  • 10
  • 20
  • You want to retrieve baseAddress from your appConfig with linq? – marvc1 Jul 09 '12 at 15:01
  • Why do you want to do this with linq? There are standard ways to work with config files. You can let Visual Studio generate a (resource) object for you to read the values from the config file. After that you can use the replace function to change a value. – Split Your Infinity Jul 09 '12 at 15:03
  • You need to give the complete path of the element in your config to help you. If its something under app settings then you are easy to use ConfiguratioinManager.AppSettings – Rajesh Jul 09 '12 at 15:05
  • i have updated my question... please look into that – user1410658 Jul 09 '12 at 15:07
  • Maybe this answer will help: http://stackoverflow.com/questions/505566/loading-custom-configuration-files/506637#506637 – Oliver Jul 09 '12 at 15:11
  • It looks quite similar to this, here i am parsing the `web.config` using `linq` do have a look https://stackoverflow.com/a/51213872/3057246 – Vinod Srivastav Sep 03 '18 at 15:32

1 Answers1

7

Parsing the app.Config file as xml and using Linq isn't the way to get settings from App.Config. Instead use System.Configuration.ddl (add a reference to this file in your project).

E.g.

string baseAddress = ConfigurationManager.AppSettings["baseAddress"].ToString();
marvc1
  • 3,641
  • 3
  • 25
  • 34
  • yes but these app.config files are not in the same class library.They in different locations so i felt using linq – user1410658 Jul 09 '12 at 15:09
  • 1
    It's v. bad practice to access variables held in another libraries config file because you cannot guarantee their validity. Instead when you construct an instance of an object in the library pass the values in the constructor. – marvc1 Jul 09 '12 at 15:12