c# - 如何获取项目之间共享的app.settings文件的相对文件路径

标签 c# asp.net visual-studio filepath appsettings

我的解决方案根目录中有一个 appsettings.config 文件,显示在我想在 3 个不同项目中引用的“解决方案项目”文件夹中

enter image description here

这3个项目包括以下内容

  • 网络性能和负载测试项目
  • 单元测试项目(UI 自动化测试)
  • 标准类库

我在类库项目中有一个配置文件的静态包装器,我打算从其他项目中引用它。

我遇到的问题是获取解决方案根目录的正确相对路径,无论当时正在运行哪个项目。

这是我的包装类代码....

public static class TestConfiguration
{
    private static Configuration Config { get; }

    static TestConfiguration()
    {
        var map = new ExeConfigurationFileMap();

        map.ExeConfigFilename = Path.Combine(@"../../../appsettings.config");

        Config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
    }

    public static string SepaTestDb {
        get { return Config.ConnectionStrings.ConnectionStrings["SEPATest"].ConnectionString; }
    }

    public static string ApiUrl => Config.AppSettings.Settings["apiUrl"].Value;
}

这适用于负载测试项目,但我得到的其他项目......

System.NullReferenceException occurred
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=SA.SEPA.Web.UI.Selenium.Integration

...当我尝试获取 SepaTestDb 或 ApiUrl 属性时,可能是由于对象未从无效文件路径初始化

我如何设置一个相对路径,以便 appsettings.config 文件可以从不同的项目访问,并且如果任何项目正在构建中/在云中等运行,将被拾取。

编辑

..这是我的 appsettings.config 文件内容

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="SEPATest" connectionString="Server=[server];Database=SEPA-c7455a3a-86bd-4862-bb25-2b5d17d97f95Test;User Id=[username];Password=[password];" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="apiUrl" value="https://sasepaapi-sasepaapitest.azurewebsites.net/api" />
  </appSettings>
</configuration>

非常感谢,

最佳答案

解决方案一:主要用于开发,不允许在运行环境共享配置文件

您可以链接 appsettings.config 到每个项目(Add Item As Link)

然后将这些链接的“复制到输出目录”属性更改为“如果较新则复制”

enter image description here

在每个项目的配置文件中使用如下:

...    
<appSettings configSource="appsettings.config" />
...

更新:

方案二:支持共享运行环境配置文件

用于在公共(public)位置托管 appsettings.config 您还可以在项目的配置文件中使用它:

...
<appSettings file=".\..\..\..\appsettings.config" />
...

或者

绝对路径

...
<appSettings file="C:\tmp\appsettings.config" />
...

您可以通过 ConfigurationManager.AppSettings[] 访问这些设置。加载该文件不需要额外的工作。

关于c# - 如何获取项目之间共享的app.settings文件的相对文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46979297/

相关文章:

c# - 看到 "cannot convert expression to type while using a generic method"时我做错了什么?

c# - 将数字四舍五入到下一个最高的 10

c# - 想从 gridview 中的日期中删除时间,但我使用了数据适配器和数据表

c# - 调用 PostAsJsonAsync 时请求被中止 : Could not create SSL/TLS secure channel.

c++ - 制作。如何生成具有不同库类型的 Visual Studio 解决方案?

c# - 我有一个 C# 解决方案,其中同一个文件属于多个项目。如何?

c# - 隐式运算符和泛型类

c# - BinaryReader.Dispose(bool disposing) 创建流的本地引用。为什么?

asp.net - 如何在 ASP.NET Identity 2.0 alpha 1 中使用电子邮件登录?

matlab - Matlab中有debug和release配置吗