简体   繁体   中英

Reading configuration file from .NET Source Project, not from target

In .NET solutions, we can read settings from configuration files, such as web.config or app.config . But I found a problem while using these resources. In a solution, I created a Class Library Project and an ASP.NET Project, both of them have a "something.config" file. In Class Library, it is called App.Config , and in ASP.NET, obviously, Web.config .

I created a method in a class in the Class Library Project and invoked it in ASP.NET. These methods gets some settings from app.config , but if I try to use in my Web project, the method read from web.config , in ASP.NET project, what is not desirable.

How can I do to make the method in Class Library Project read the App.Config from corresponding project, not from web project?

It depends on the application you are running.

The web application is the entry point hence it'll use the web.config.

You can put the values/sections contained in the app.config into the web.config and it'll be read.

After digging out the configuration manager class i've added the below to read config file associated with an assembly.

var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);

var tempValue = config.AppSettings["setting_name"];

App.config that places in the class library project wouldn't load by default. The only config file will be loaded is the client configuration ( web.config ).

To configure the project to load the local class library config file which is app.config .

You need the following code to do that:

ConfigurationManager.OpenMappedExeConfiguration(
    new ExeConfigurationFileMap() { 
        ExeConfigFilename = path + "app.config" 
    }, ConfigurationUserLevel.None);

For more details, visit this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM