本文介绍了如何在.NET Core 2 classlib项目中使用C#从.csproj文件读取/获取PropertyGroup值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to get the value of the element <Location>SourceFiles/ConnectionStrings.json</Location> that is child of <PropertyGroup /> using C#. This is located at the .csproj file for a .NET Core 2 classlib project. The structure is as follow:

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

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

Which class can I use from .NET Core libraries to achieve this? (not .NET framework)

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

Update 1:I want to read the value when the application (that this .csproj file builds) runs. Both before and after deployment.

谢谢

推荐答案

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

As has been discussed in comments, csproj content only controls predefined build tasks and aren't available at run-time.

但是msbuild很灵活,可以使用其他方法将某些值持久化以在运行时可用.

But msbuild is flexible and other methods could be used to persist some values to be available at run time.

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

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

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

which can then be used in the auto-generated assembly attributes from inside the csproj file:

<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}");
}

这篇关于如何在.NET Core 2 classlib项目中使用C#从.csproj文件读取/获取PropertyGroup值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:26