简体   繁体   中英

Config files for assemblies in GAC

I have a .NET dll which needs to read it's config settings from it's config file. Usually, the config file is placed in the same directory as the DLL. But how do i read the config file if the DLL is GAC'ed, because I can put only the DLLs in the GAC, and not it's config files.

Does the user need to configure the Dll? If so, then the DLL should be using configuration settings from the app.config file, not it's own config. The app.config file should be stored in the same directory as the application. If not, then you could go a couple of different ways. You could make changes to the machine.config file so that your Dll can find them there. I would not do this. Alternatively, you can store the configuration in a settings class. These can be overridden via configuration, but your defaults will be set in the generated code for the settings class via attributes and so the absence of a configuration file will not affect your Dll when the defaults are all that are required.

I agree with tvanfosson the Gac'ed dll will read from the application's path. But you could also inform the dll which is the path in this way:

System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
fileMap.ExeConfigFilename = "THE PATH TO THE CONFIG";
System.Configuration.Configuration cfg =
System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);

string thevalue=cfg.AppSettings.Settings[variable].Value;

You can make use of AppDomain.CurrentDomain.BaseDirectory since the DLL library will not be executed by itself you just need to get Executable file directory who is calling him

Something like:

var appDomain = AppDomain.CurrentDomain.BaseDirectory;
string sFileName = appDomain.Replace("\\bin\\Debug", "");
sFileName = sFileName + "Config\\config.xml";

Here my executable is in folder bin\\Debug and inside the folder i have a folder called Config where i have the xml config file config.xml . So the sFileName will provide you the relative path to the config file as \\bin\\Debug\\Config\\config.xml

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