.net Core parse csproj file to object
Asked Answered
M

1

6

The problem- We can parse a csproj file in some ways, but most of the information is not in the file, but is either by default or affected by other properties.

I want to work against csproj files and solution- get project dependencies, get properties and items (things like 'TargetFramework', compiled files..)

The TargetFramework can be a tag with value, or 'TargetFrameworks' tag with multi-values that parsed to 'TargetFramework'.

The old solution- MSBuild provide a microsoft.build.evaluation library to work with csproj file, but this library compiled to net471, and cause errors when we use it in netcoreapp.

What will be the solution for the problem, in .net core projects?

Middleweight answered 17/12, 2018 at 7:0 Comment(7)
At the moment it's quite hard to know how to answer this, as we don't know what you're trying to achieve. What's the bigger goal here? There are various packages such as Microsoft.Build, Microsoft.Build.Framework etc, but we won't know whether or not they'll be of any use to you if we don't know what you're trying to achieve.Robbierobbin
@JonSkeet Edited. About Microsoft.Build, Microsoft.Build.Framework, as I said, it compiled to net471 only.Middleweight
Well, you said about Microsoft.Build.Evaluation - I assumed that was a NuGet package, although I can't find it on nuget.org. Both Microsoft.Build and Microsoft.Build.Framework include netstandard2.0 targets, so should be fine with netcoreapp2.0.Robbierobbin
You are right, but I can't find an object that represents csproj files in Microsoft.Build or Microsoft.Build.FrameworkMiddleweight
If you're happy going down a Roslyn-based route, I think Microsoft.CodeAnalysis.Workspaces.MSBuild may be what you're after. You might also want to look at github.com/KirillOsenkov/MSBuildStructuredLog for a complete working code example.Robbierobbin
There are also projects like Buildalyzer that abstracts a lot of the configuration needed to get the Microsoft.Build.* packages working the right way on every platform, but I can't tell if it's features can help you..Erode
@Martin Thank you, I left an issue in this project.Middleweight
P
10

For .Net Core Microsoft.Build NuGet Package works as below:

var projectRootElement = ProjectRootElement.Open(csprojPath);
projectRootElement.AddProperty("Version", "3.4.5");
projectRootElement.Save();

If Version exists it overrides it. If not exist adds new property name is "Version" and value is "3.4.5".

Also you can get all properties which defined in .csproj

var projectRootElement = ProjectRootElement.Open(csprojPath);
foreach (var property in projectRootElement.Properties)
{
    Console.WriteLine($"Name: {property.Name} - Value: {property.Value}");
}

Tested in .NetCore 5.0

Pidgin answered 15/6, 2021 at 7:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.