Accessing another projects app.config properties?

久未见 提交于 2019-11-26 20:54:39

问题


I have two projects within my solution, for this example I will call them project A and B.

Project B references A. Can Project B access the app.config properties of project A?

I wish to access an app key string within the app.config of A.

string tfsUri = ConfigurationManager.AppSettings["TfsUri"];

回答1:


That's generally not a good idea, as you introduce hard dependencies between the projects. So if you can copy-paste config value, that will make your projects self-contained (however, this introduces duplication of config value).

You can also automate this, so that when you build a project the configuration dependency is automatically resolved.

Having-said this, there are other options, and in each case you may prefer to use something else. Your other options are:

  • Use configuration transformation, like SlowCheetah
  • Add whole config file from one project to another "as a link"
  • Inject configuration value to your class (instead of reading it from config)
  • Read other project's config file in runtime, by using things like ConfigurationManager.OpenExeConfiguration
  • Also check out How to select different app.config for several build configurations



回答2:


       var path = @"C:\Users\Stephen\source\repos\SensurityConfigurationTool\Configuration.UI\App.config";
        string directory = Path.GetDirectoryName(path);
        var pathRoot = Path.GetPathRoot(directory);
        string file = Path.GetFileName(path);


        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap
        {
            ExeConfigFilename = Path.Combine(Path.GetFullPath(directory + "\\" + file))
        };

        System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

You basically get the relative path, then convert this to an absolute path



来源:https://stackoverflow.com/questions/22785541/accessing-another-projects-app-config-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!