Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Web.config from another Project

Tags:

c#

I am writing a test platform for some semi-automated testing using a Console application, but I need to get the connection string from the project I am testing. I don't want to reference the other application directly or otherwise have an accessor in the project I'm testing.

What I've managed to do so far is create a link to the other project's Web.config file in my TestUtility project, and I've set it to Copy if newer. It's the only Web.config in my test project's root folder, but WebConfigurationManager.OpenWebConfiguration(null) seems to be opening some OTHER Web.config, as the only connection string in it refers to .\SQLEXPRESS (not in any file in my solution, my path would be .\sql2008 in this configuration - which varies).

Any hints or tips as to how to access that config section from another project?

(Yay first question)

like image 855
Rob G Avatar asked Apr 05 '13 16:04

Rob G


People also ask

Can we have 2 web config?

Yes you can have two web. config files in application. There are situations where your application is divided in to modules and for every module you need separate configuration. For example if you have a application which has two modules lets say accounts and sales.

Where can I find web config?

The Web. Config file is used to configure Oracle Web Application functionality. This file is typically installed in the c:\Inetput\wwwroot\WebApp directory.


2 Answers

Better late than never:

var filePath = @"D:\PathToConfig\Web.config";
var map = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
var configFile = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

I can't take the credit for this one though, I found it here!

like image 176
Gabriel Avatar answered Sep 20 '22 18:09

Gabriel


The solution I found was to open it as an XDocument and parse it manually:

        XDocument xdoc = XDocument.Load("Test/Web.config");

        var path = xdoc.Element("configuration").Element("connectionStrings").Element("add").Attribute("connectionString").Value;

Though if you had multiple connection strings, you would want to use the .Elements("add") method on the connectionStrings element and iterate over the various strings.

like image 40
Rob G Avatar answered Sep 22 '22 18:09

Rob G