繁体   English   中英

如何在.NET Core 2 classlib项目中使用C#从.csproj文件读取/获取PropertyGroup值?

[英]How to read/get a PropertyGroup value from a .csproj file using C# in a .NET Core 2 classlib project?

我想使用C#获取<PropertyGroup />子元素<Location>SourceFiles/ConnectionStrings.json</Location>值。 它位于.NET Core 2 classlib项目的.csproj文件中。 结构如下:

<PropertyGroup>
  <TargetFramework>netcoreapp2.0</TargetFramework>
  <Location>SharedSettingsProvider.SourceFiles/ConnectionStrings.json</Location>
</PropertyGroup>

我可以从.NET Core库中使用哪个类来实现此目的? (不是.NET框架)

更新1:我想在应用程序(此.csproj文件构建)运行时读取值。 在部署之前和之后。

谢谢

正如在注释中所讨论的,csproj内容仅控制预定义的构建任务,并且在运行时不可用。

但是msbuild是灵活的,并且可以使用其他方法来保持某些值在运行时可用。

一种可能的方法是创建自定义程序集属性:

[System.AttributeUsage(System.AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
sealed class ConfigurationLocationAttribute : System.Attribute
{
    public string ConfigurationLocation { get; }
    public ConfigurationLocationAttribute(string configurationLocation)
    {
        this.ConfigurationLocation = configurationLocation;
    }
}

然后可以在csproj文件中使用自动生成的程序集属性:

<PropertyGroup>
  <ConfigurationLocation>https://my-config.service/customer2.json</ConfigurationLocation>
</PropertyGroup>
<ItemGroup>
  <AssemblyAttribute Include="An.Example.ConfigurationLocationAttribute">
    <_Parameter1>"$(ConfigurationLocation)"</_Parameter1>
  </AssemblyAttribute>
</ItemGroup>

然后在运行时在代码中使用:

static void Main(string[] args)
{
    var configurationLocation = Assembly.GetEntryAssembly()
        .GetCustomAttribute<ConfigurationLocationAttribute>()
        .ConfigurationLocation;
    Console.WriteLine($"Should get config from {configurationLocation}");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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