简体   繁体   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?

I want to get the value of the element <Location>SourceFiles/ConnectionStrings.json</Location> that is child of <PropertyGroup /> using C#. 我想使用C#获取<PropertyGroup />子元素<Location>SourceFiles/ConnectionStrings.json</Location>值。 This is located at the .csproj file for a .NET Core 2 classlib project. 它位于.NET Core 2 classlib项目的.csproj文件中。 The structure is as follow: 结构如下:

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

Which class can I use from .NET Core libraries to achieve this? 我可以从.NET Core库中使用哪个类来实现此目的? (not .NET framework) (不是.NET框架)

Update 1: I want to read the value when the application (that this .csproj file builds) runs. 更新1:我想在应用程序(此.csproj文件构建)运行时读取值。 Both before and after deployment. 在部署之前和之后。

Thanks 谢谢

As has been discussed in comments, csproj content only controls predefined build tasks and aren't available at run-time. 正如在注释中所讨论的,csproj内容仅控制预定义的构建任务,并且在运行时不可用。

But msbuild is flexible and other methods could be used to persist some values to be available at run time. 但是msbuild是灵活的,并且可以使用其他方法来保持某些值在运行时可用。

One possible approach is to create a custom assembly attribute: 一种可能的方法是创建自定义程序集属性:

[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;
    }
}

which can then be used in the auto-generated assembly attributes from inside the csproj file: 然后可以在csproj文件中使用自动生成的程序集属性:

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

And then used at run time in code: 然后在运行时在代码中使用:

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