gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:22:29 24 4
gpt4 key购买 nike

我想获取元素<Location>SourceFiles/ConnectionStrings.json</Location>的值那是 <PropertyGroup /> 的 child 使用 C#。它位于 .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}");
}

关于c# - 如何在 .NET Core 2 classlib 项目中使用 C# 从 .csproj 文件读取/获取 PropertyGroup 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49522751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com