访问另一个项目的app.config属性?

我的解决方案中有两个项目,对于这个例子,我将其称为项目A和B.

项目B引用A.项目B可以访问项目A的app.config属性吗?

我希望在A的app.config中访问app键字符串。

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

这通常不是一个好主意,因为你在项目之间引入了硬依赖关系。 因此,如果您可以复制粘贴配置值,那将使您的项目自包含(但是,这会引入配置值的重复)。

您也可以自动执行此操作,以便在构建项目时自动解析配置依赖项。

说完这个,还有其他选择,在每种情况下你可能更喜欢使用别的东西。 您的其他选择是:

  • 使用配置转换,如SlowCheetah
  • 将整个配置文件从一个项目添加到另一个项目“作为链接”
  • 将配置值注入您的类(而不是从配置中读取)
  • 通过使用ConfigurationManager.OpenExeConfiguration之类的东西,在运行时读取其他项目的配置文件
  • 另请参阅如何为多个构建配置选择不同的app.config
  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); 

您基本上获得相对路径,然后将其转换为绝对路径