dotnet / dotnet/msbuild

How can we reload the project object if the underlying project file was overwritten outside of the msbuild API?

Open
#7,163 8 comments 0 reactions 0 assignees View on GitHub
backlog bug triaged
Dominant language
C#
Stars
5.5k
Forks
1.5k
Avg merge
1d 8h
Merged PRs (30d)
141

Description

### Issue Description
I have a situation where there is a `Project` object and the respective project file is restored from a backup string using `File.WriteAllText` API. My goal is to reload the `Project` object.

### Steps to Reproduce
Run the following code:

The project file:
```


Exe
net5.0



runtime



runtime



PreserveNewest

```

**Test\XMLFile1.xml**
```


Library
net472



```

**Program.cs**
```
using Microsoft.Build.Evaluation;
using Microsoft.Build.Locator;
using System;
using System.IO;
using System.Linq;
using System.Reflection;

class Program
{
static void Main()
{
MSBuildLocator.RegisterDefaults();
Console.WriteLine(Environment.GetEnvironmentVariable("MSBUILD_EXE_PATH"));
Run();
}

static void Run()
{
var projectFile = Path.GetFullPath(Assembly.GetExecutingAssembly().Location + "\\..\\Test\\XMLFile1.xml");
var backup = File.ReadAllText(projectFile);

var p = GetProject("Init", projectFile);

var item = p.GetItems("Reference").First(o => !o.IsImported);
p.RemoveItem(item);
p.Save();
p.ProjectCollection.UnloadProject(p);

p = GetProject("After modify", projectFile);

File.WriteAllText(projectFile, backup);
p.ProjectCollection.UnloadProject(p);

GetProject("After rollback", projectFile);
}

static Project GetProject(string prompt, string projectFile)
{
var p = new Project(projectFile);
var count = p.GetItems("Reference").Count(o => !o.IsImported);
Console.WriteLine(prompt + " : " + count);
return p;
}
}
```

Compile and run.

### Expected Behavior

After the file is restored the new `Project` object reflects the new file content. I.e. the output should show **After rollback : 0**

### Actual Behavior
Here is the actual output:
```
C:\Program Files\dotnet\sdk\5.0.403\MSBuild.dll
Init : 1
After modify : 0
After rollback : 0
```

### Analysis
Unloading the project from the collection does not seem to affect the ProjectRootElementCache, which seems to hold on to the `Xml` of the project.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.