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

[亡魂溺海] 提交于 2019-12-06 07:13:26

问题


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>

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

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

Thanks


回答1:


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

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

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


来源:https://stackoverflow.com/questions/49522751/how-to-read-get-a-propertygroup-value-from-a-csproj-file-using-c-sharp-in-a-ne

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!