【问题标题】:How to read/get a PropertyGroup value from a .csproj file using C# in a .NET Core 2 classlib project?如何在 .NET Core 2 类库项目中使用 C# 从 .csproj 文件中读取/获取 PropertyGroup 值?
【发布时间】:2018-09-06 10:40:38
【问题描述】:

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

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

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

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

谢谢

【问题讨论】:

  • 你能说明你想做什么吗?您想在您的应用程序(此 csproj 文件构建的)运行时(可能在部署到服务器之后)读取该值吗?或者你有一个单独的应用程序需要从这个 csproj 文件中读取值?你到底想做什么?
  • @omajid 更新 1 阐明了我想要什么。谢谢
  • 哦。恐怕这是不可能的。 csproj 文件用于构建,在运行时不存在。所以你不能从中读取值。您可以在构建期间写出一个配置文件(该配置文件将包含变量/值)并将该配置文件放在应用程序旁边,您的应用程序可以在运行时找到它。

标签: c# msbuild .net-core asp.net-core-2.0 csproj


【解决方案1】:

正如在 cmets 中所讨论的,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}");
}

【讨论】:

  • 提醒下一个人:GetEntryAssembly() 可能与正在执行的程序集不同...
  • 我无法使用此示例访问类型 ConfigurationLocationAttribute。如果我在 .csproj 文件中使用 Compile 标记,那么它会编译但在运行时不起作用。如果我使用AssemblyAttribute 标记,如此处所示,我无权访问该类型并且项目无法编译(您的 Main 方法不会为我编译)。
  • @DanRayson 你能提供一个完整的例子吗?也许创建一个新问题?这里唯一没有完全解释的是将An.Example. 替换为应用程序使用的命名空间。当项目的程序集信息生成被禁用时它也不起作用(但它应该编译但在运行时失败)
  • @MartinUllrich 事实证明这是我的错误 - 我通过 Visual Studio 传递参数(实际上并没有让你这样做,因此我的错误),一旦我开始使用 @987654329 @ 直接在命令提示符中,它工作得很好。为浪费时间道歉。有点烦人,我不能改变我的投票:/
  • 对于那些想在 .Net Framework 中做这种事情的人,you have to add a couple more bits to the csproj file to make it work,否则根本不写属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
  • 2011-07-30
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多