Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify programatically csproj files with Microsoft.Build.Evaluation (instead of Engine)

I would like to read, modify and write back csproj files. I've found this code, but unfortunately Engine class is depreciated.

Engine engine = new Engine()
Project project = new Project(engine);
project.Load("myproject.csproj");
project.SetProperty("SignAssembly", "true");
project.Save("myproject.csproj");

So I've continued based on the hint I should use Evaluation.ProjectCollection instead of Engine:

var collection = new ProjectCollection();
collection.DefaultToolsVersion = "4.0";
var project = new Project(collection);

// project.Load("myproject.csproj") There is NO Load method :-(
project.FullPath = "myproject.csproj"; // Instead of load? Does nothing...

// ... modify the project
project.Save(); // Interestingly there is a Save() method

There is no Load method anymore. I've tried to set the property FullPath, but the project still seems empty. Missed I something?

(Please note I do know that the .csproj file is a standard XML file with XSD schema and I know that we could read/write it by using XDocument or XmlDocument. That's a backup plan. Just seeing the .Save() method on the Project class I think I missed something if I can not load an existing .csproj. thx)

like image 292
g.pickardou Avatar asked Apr 09 '14 09:04

g.pickardou


People also ask

How do I open and edit Csproj in Visual Studio?

You should be able to do this by right clicking the project in the Solution window and selecting Tools - Edit File. That will open the project file (. csproj) in the text editor.

What program opens Csproj?

CSPROJ files are are meant to be opened and edited in Microsoft Visual Studio (Windows, Mac) as part of Visual Studio projects.

What is a Csproj file extension?

Files with CSPROJ extension represent a C# project file that contains the list of files included in a project along with the references to system assemblies. When a new project is initiated in Microsoft VIiual Studio, you get one . csproj file along with the main solution (. sln) file.


1 Answers

I've actually found the answer, hopefully will help others:

Instead of creating a new Project(...) and trying to .Load(...) it, we should use a factory method of the ProjectCollection class.

// Instead of:
// var project = new Project(collection);
// project.FullPath = "myproject.csproj"; // Instead of load? Does nothing...

// use this:
var project = collection.LoadProject("myproject.csproj")
like image 57
g.pickardou Avatar answered Oct 20 '22 02:10

g.pickardou