[c#] How to find path of active app.config file?

I'm trying to finish this exception handler:

if (ConfigurationManager.ConnectionStrings["ConnectionString"]==null)
{
    string pathOfActiveConfigFile = ...?
    throw new ConfigurationErrorsException(
       "You either forgot to set the connection string, or " +
       "you're using a unit test framework that looks for  "+
       "the config file in strange places, update this file : " 
       + pathOfActiveConfigFile);
}

This problem seems to only happen to me when I'm using nUnit.

This question is related to c# .net nunit app-config configurationmanager

The answer is


I tried one of the previous answers in a web app (actually an Azure web role running locally) and it didn't quite work. However, this similar approach did work:

var map = new ExeConfigurationFileMap { ExeConfigFilename = "MyComponent.dll.config" };
var path = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None).FilePath;

The config file turned out to be in C:\Program Files\IIS Express\MyComponent.dll.config. Interesting place for it.


Make sure you click the properties on the file and set it to "copy always" or it will not be in the Debug\ folder with your happy lil dll's to configure where it needs to be and add more cowbell


One more option that I saw is missing here:

const string APP_CONFIG_FILE = "APP_CONFIG_FILE";
string defaultSysConfigFilePath = (string)AppDomain.CurrentDomain.GetData(APP_CONFIG_FILE);

If you mean you are only getting a null return when you use NUnit, then you probably need to copy the ConnectionString value the your app.config of your application to the app.config of your test library.

When it is run by the test loader, the test assembly is loaded at runtime and will look in its own app.config (renamed to testAssembly.dll.config at compile time) rather then your applications config file.

To get the location of the assembly you're running, try

System.Reflection.Assembly.GetExecutingAssembly().Location

Depending on the location of your config file System.Reflection.Assembly.GetExecutingAssembly().Location might do what you need.


Strictly speaking, there is no single configuration file. Excluding ASP.NET1 there can be three configuration files using the inbuilt (System.Configuration) support. In addition to the machine config: app.exe.config, user roaming, and user local.

To get the "global" configuration (exe.config):

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
                    .FilePath

Use different ConfigurationUserLevel values for per-use roaming and non-roaming configuration files.


1 Which has a completely different model where the content of a child folders (IIS-virtual or file system) web.config can (depending on the setting) add to or override the parent's web.config.


The first time I realized that the Unit testing project referenced the app.config in that project rather then the app.config associated with my production code project (off course, DOH) I just added a line in the Post Build Event of the Prod project that will copy the app.config to the bin folder of the test project.

Problem solved

I haven't noticed any weird side effects so far, but I am not sure that this is the right solution, but at least it seems to work.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to nunit

How can I run NUnit tests in Visual Studio 2017? Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds NUnit Unit tests not showing in Test Explorer with Test Adapter installed How can we run a test method with multiple parameters in MSTest? Verifying a specific parameter with Moq How do I use Assert.Throws to assert the type of the exception? How to find path of active app.config file? NUnit vs. MbUnit vs. MSTest vs. xUnit.net HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

Examples related to app-config

Is ConfigurationManager.AppSettings available in .NET Core 2.0? How to read AppSettings values from a .json file in ASP.NET Core What is App.config in C#.NET? How to use it? How to make spring inject value into a static field App.Config change value Get connection string from App.config How should I edit an Entity Framework connection string? Equivalent to 'app.config' for a library (DLL) How to implement a ConfigurationSection with a ConfigurationElementCollection App.Config Transformation for projects which are not Web Projects in Visual Studio?

Examples related to configurationmanager

SCCM 2012 application install "Failed" in client Software Center AppSettings get value from .config file ConfigurationManager.AppSettings - How to modify and save? How to get the values of a ConfigurationSection of type NameValueSectionHandler How to check if an appSettings key exists? How to find path of active app.config file?