Why does loading a Xamarin Android .csproj into a Microsoft.Build.Evaluation.Project throw InvalidPropectFileException due to missing .targets file?

Viewed 525

I am attempting to open a Xamarin Android .csproj file in a .NET 5.0 console application using an instance of Microsoft.Build.Evaluation.Project. Additionally I have also attempted to do the same with a .NET Framework 4.6.1 project.

The code for loading is:

var fileName = @"C:\Users\vchel\source\repos\BlankAndroid\BlankAndroid\BlankAndroid.csproj";
var project = new global::Microsoft.Build.Evaluation.Project(fileName, null, null, new ProjectCollection());

When I attempt to instantiate the Project object, I get the following exception:

Microsoft.Build.Exceptions.InvalidProjectFileException: 
The imported project "C:\Users\vchel\source\repos\ProjectLoadTest\ProjectLoadTest\bin\Debug\net5.0\Xamarin\Android\Xamarin.Android.CSharp.targets" was not found.
Confirm that the expression in the Import declaration "C:\Users\vchel\source\repos\ProjectLoadTest\ProjectLoadTest\bin\Debug\net5.0\Xamarin\Android\Xamarin.Android.CSharp.targets" is correct, and that the file exists on disk.  C:\Users\vchel\source\repos\BlankAndroid\BlankAndroid\BlankAndroid.csproj

The Xamarin.Android.CSharp.targets file referenced in the error above appears in the .csproj that I am loading as shown in the following snippet:

  <Import Project="$(MSBuildExtensionsPath)\Xamarin\Android\Xamarin.Android.CSharp.targets" />

Notice that the .csproj references the Xamarin.Android.CSharp.targtets file with the $(MSBuildExtensionPath) prefix, but at runtime this is swapped with the location of the running console application .exe rather than

The Android project which I am attempting to load opens correctly in Visual Studio and compiles/runs with no problems.

Why does this Android project open without any problems in Visual Studio, yet it fails when attempting to open in a Microsoft.Build.Evaluation.Project object?

1 Answers

It seems I've actually run into this same problem before, but it wasn't on an Android project so I'll keep this question here to address Android-specific issues.

The problem in general is discussed here:

How to Load .csproj file into .NET Core 3.0 using MSBuild NuGet

The summary is - the .target files are separate from the nuget packages being installed, and it seems like the Project class can't resolve $(MSBuildExtensionsPath). Therefore, to solve this problem the relevant .targets files should be added to the project and copied to the output (bin) folder.

On my machine, the original files can be found in:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Xamarin\Android

I had to add the following files to my app. Notice they are added to the Xamarin/Android/ folder:

enter image description here

Items can be marked as Copy if newer:

enter image description here

Related