views:

153

answers:

3

Little embarrassed to ask, but since I never had to do it, here it goes. I have a config file that has connection strings for the app stored in this format.

<connectionStrings>
    <clear />
    <add name="MyConnectionStringName" connectionString="{here is a connection string}"/>
</connectionStrings>

I tried ConfigurationManager but it requires that the file has "configuration" root element. Is there something else in Configuration name space, or should I just use LinqToXml?

Update: I cannot change anything in the file, file is already in the use for years by some in home grown framework. All content that is in the file is shown above.

Update2: Second look reveals that this file is referenced from App.Config as

  <connectionStrings configSource="Config\connectionstrings.config"/>

which allows me to use ConfigurationManager.ConnectionStrings.

A: 

What's wrong in

<Configuration>
  <appSettings>
    <add key="MyConnectionStringName" value="{here is a connection string}"/>
  </appSettings>
</Configuration>
Dani
it is an old app, that has some crappy framework build around it, and I cannot change it.
epitka
+1  A: 

There is more to a configuration file than just the connectionStrings section. If you are using Visual Studio, the easy way to fix your problem is to use the IDE to add a new Application Configuration file. The IDE will create a shell file for you, which you can then add your connectionStrings section to (within the configuration section).

By hand, at bare minimum, you need this:

<?xml version="1.0"?>
<configuration>
    <connectionStrings>
        <clear />
        <add name="MyConnectionStringName" connectionString="{connection string}"/>
    </connectionStrings>
</configuration>
Matt Hamsmith
A: 

Well you could load it into an XmlDocument and the Load method.

Once you have it loaded you can use SelectNodes with an xpath query to get back the nodes you want.

Off the top of my head something like

string conn;
XmlDocument xdoc = new XmlDocument();
xdoc.Load("path_to_file");
var configs = xdoc.SelectNodes("ConnectionStrings/Add");
foreach(XmlNode n in configs)
{
     conn = n.Attributes["connectionString"];
}

Try that and see. you may need to play around with the xpath, been a while since i wrote one.

Kaius