Error msb4057 the target gettargetpath does not exist in the project

There is a problem with solution dependencies that I believe was introduced with MSBuild 15.9, and is also a problem with 16.0. The following scenario causes the problem; There is a project that ha...

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Open

bording opened this issue

Apr 11, 2019

· 21 comments

Comments

@bording

There is a problem with solution dependencies that I believe was introduced with MSBuild 15.9, and is also a problem with 16.0.

The following scenario causes the problem;

  • There is a project that has <GeneratePackageOnBuild>true</GeneratePackageOnBuild> set
  • It has a solution dependency on a second project, and that project is multi-targeted.

Steps to reproduce

Build the attached project with MSBuild.exe or dotnet build: GetTargetPathRepro.zip

Expected behavior

The solution should compile without errors.

Actual behavior

The following error occurs:

"C:UsersBrandonsourcereposGetTargetPathReproGetTargetPathRepro.sln" (default target) (1:2) ->
"C:UsersBrandonsourcereposGetTargetPathReproClassLibrary1ClassLibrary1.csproj.metaproj" (default target) (4) ->
"C:UsersBrandonsourcereposGetTargetPathReproClassLibrary1ClassLibrary1.csproj" (default target) (2:6) ->
"C:UsersBrandonsourcereposGetTargetPathReproClassLibrary1ClassLibrary1.csproj" (_GetFrameworkAssemblyReferences target) (2:10) ->
"C:UsersBrandonsourcereposGetTargetPathReproClassLibrary2ClassLibrary2.csproj" (GetTargetPath target) (3:15) ->
  C:UsersBrandonsourcereposGetTargetPathReproClassLibrary2ClassLibrary2.csproj : error MSB4057: The target "GetTargetPath" does not exist in the project.

    0 Warning(s)
    1 Error(s)

Environment data

It repros with MSBuild 15.9.21.664 and 16.0.461.62831.
It also repros with .NET Core SDK 2.2.106 and 3.0.100-preview3-010431

I believe it worked fine before MSBuild 15.9, but I don’t know an exact version.

@rainersigwald

This is fairly involved. It’s related to 3258497, which was in 15.8.

NuGet packaging calls _GetFrameworkAssemblyReferences which builds the current project (ClassLibrary1) with a specified TargetFramework and BuildProjectReferences = false. That is a distinct build from the «real» build of that project, so it creates a new project instance. That instance then tries to ResolveProjectReferences, which fails because when BuildProjectReferences != true, it calls GetTargetPath instead of the default target. That then fails, because GetTargetPath isn’t defined for the outer build of a multitargeted project.

I think NuGet should special case the GeneratePackageOnBuild case for a single-targeted project to collapse to the current build, which already has references resolved.

This can be worked around by adding a Directory.Build.props for your solution with this property:

<Project>
 <PropertyGroup>
  <AddSyntheticProjectReferencesForSolutionDependencies>false</AddSyntheticProjectReferencesForSolutionDependencies>
 </PropertyGroup>
</Project>

@bording

Since building from Visual Studio seems work fine and not result in an error, I assume that’s because it has a different way of invoking all of this?

This can be worked around by adding a Directory.Build.props for your solution with this property:

The workaround I came up with that seems to be working was to switch to a ProjectReference with
ReferenceOutputAssembly="false" and PrivateAssets="All" set.

@bording

I think NuGet should special case the GeneratePackageOnBuild case for a single-targeted project to collapse to the current build, which already has references resolved.

I could be misunderstanding what you’re saying here, but the problem still occurs when ClassLibrary1 is multi-targeted a well.

@rainersigwald

Since building from Visual Studio seems work fine and not result in an error, I assume that’s because it has a different way of invoking all of this?

Yes, unfortunately. VS builds projects in a solution using a pretty different mechanism from MSBuild’s solution handling.

The workaround I came up with that seems to be working was to switch to a ProjectReference with
ReferenceOutputAssembly="false" and PrivateAssets="All" set.

Yeah, if that works for you I’d prefer it over a solution dependency—it’s clearer from the MSBuild side.

@sebashek

FWIW, I had 2 references to the same project within the solution. Opening the csproj file with a text editor indicated that (Visual Studio did not, neither did a ‘remove project reference’ > ‘add project reference’).

The 2 references had different guids, 1 of them was the incorrect one.

@matiasdd

I had the same error and somewhat similar to @sebashek, I had two identical project references listed in a single project file. Removing one of the references fixed the issue.

kditrj2d, MikeJansen, sundeepyama, Ross-cz, he-dev, Squazz, micahosborne, grgsweta, beefo, martin-corevski, and 6 more reacted with thumbs up emoji
micahosborne and wilbit reacted with hooray emoji
fuyfuy reacted with heart emoji

@bording

@rainersigwald I see this still has no milestone. Any plans to address at some point?

@bizzbizz

I had the same issue. When I modified a project and changed its assembly name, an NUnitTest project referencing the modified project couldn’t build anymore. Other projects referencing the modified project wasn’t affected.

I noticed that this error was purely because of a space in the middle of the new AssemblyName of the modified project. When I removed the space NUnit project started working again.

This bug is basically preventing me from having a space in name of any assembly which has a unit test.

workaround: rename assembly and remove spaces

@coderb

i’m getting this error in visual studio 2019 using a solution with a mix of old-style and new style multi-targeted csproj files.

not sure where to go from here.

@jbennink

Not sure if this is related But I came here for the error, whil inspecting my csporj I noticed I had somehow included the same projectreference twice! After removing the duplicate my error went away. So at least there are more reasons that you can get this error

@rokups

This is very problematic for CMake projects that use include_external_msproject() to add manually crafted multi-target C# projects. Workaround does not work in this case.

@Ian1971

I had the same double project reference in the csproj as others, removing that fixed it.

SimonCropp

added a commit
to Fody/Fody
that referenced
this issue

Mar 27, 2021

@SimonCropp

tom-englert

added a commit
to tom-englert/SplashScreen.Fody
that referenced
this issue

May 31, 2021

@tom-englert

@NorbertNemec

@rokups — did you find a solution for the problem with include_external_msproject()? I seem to be stumbling over the same issue.

@rokups

I do not remember. I am not dealing with this issue any more, but i can not find any relevant commits from the time of my post. Not sure if this happened in some experimental branch that i later scrapped… Sorry for being useless :|

@NorbertNemec

After long struggles with the problem using include_external_msproject() I finally found an applicable workaround on wixtoolset/issues#5705:

  <Target Name="GetTargetPath" Returns="@(_FakeOutputPath)">
    <ItemGroup>
      <_FakeOutputPath Include="$(MSBuildProjectDirectory)$(PackageOutputPath)$(AssemblyName).dll" />
    </ItemGroup>
  </Target>

@benmccallum

I seemed to get this after changing TargetFramework —> TargetFrameworks. The project I did this in started failing to build, but only in builds with other projects that depended on it (worked when I built it by itself). In the end I only needed one target framework so dropped the s again and that seemed to force VS to re-evaluate something that no amount of cleaning/rebuilding or opening/closing VS could solve. 🤷🏻‍♂️

@ghidalgo3

@kwaazaar

I added a comment to your report @ghidalgo3. It’s too complicated to create a simple repro though.

NightOwl888

added a commit
to NightOwl888/ICU4N
that referenced
this issue

Mar 24, 2022

@NightOwl888

NightOwl888

added a commit
to NightOwl888/ICU4N
that referenced
this issue

Mar 24, 2022

@NightOwl888

@TheRealAyCe

I had the same issue. When I modified a project and changed its assembly name, an NUnitTest project referencing the modified project couldn’t build anymore. Other projects referencing the modified project wasn’t affected.

I noticed that this error was purely because of a space in the middle of the new AssemblyName of the modified project. When I removed the space NUnit project started working again.

This bug is basically preventing me from having a space in name of any assembly which has a unit test.

workaround: rename assembly and remove spaces

This was the fix for me, using xUnit. My Test assembly was referencing several projects, and the problems were only with the ones that had spaces in them, but I never would have thought that this sort of thing would still cause problems in 2022.

@dotMorten

For me this issue got introduced when I started setting TargetPlatformMinVersion in the UWP project, because I wanted a smaller min-version but wanted to use the newer SDK. Only happens to the project referencing the multi-targeted project (which have the same min/max versions for UWP).
image

@dotMorten

Found a workaround for UWP case: In the second project pluralize TFM so it says TargetFrameworks and problem goes away 🤦

We are migrating our compilation system to msbuild, and we’ve found that some projects report the following error:

c:srclibsa_libAA.vcxproj : error MSB4057: The target «C» does not exist in the project.

c:srclibsa_libBB.vcxproj : error MSB4057: The target «C» does not exist in the project.

c:srclibsa_libCC.vcxproj : error MSB4057: The target «C» does not exist in the project.

c:srclibsa_libDD.vcxproj : error MSB4057: The target «C» does not exist in the project.

The compilation line is

msbuild "c:srclibsa_liba_lib.sln" /nologo "/target:C" /t:build "/p:Configuration=Release" "/p:Platform=Win32"

As can be seen, the solution has several projects. The project itself exists in the solution and can be compiled from within the VS IDE. Also, other targets do not fail (following the example: A, B, D).

Our previous compilation line worked correctly on the same project:

devenv "c:srclibsa_liba_lib.sln" /project "C" /build /nologo "Release|Win32"

Это довольно сложно. Это связано с https://github.com/Microsoft/msbuild/commit/3258497c668ff3d0cd699975923b6cd593a1703d , который был в версии 15.8.

Пакетирование NuGet вызывает _GetFrameworkAssemblyReferences который создает текущий проект (ClassLibrary1) с указанными TargetFramework и BuildProjectReferences = false . Это сборка, отличная от «настоящей» сборки этого проекта, поэтому она создает новый экземпляр проекта. Затем этот экземпляр пытается выполнить ResolveProjectReferences , что не удается, потому что при BuildProjectReferences != true он вызывает GetTargetPath вместо цели по умолчанию. Это затем терпит неудачу, потому что GetTargetPath не определено для внешней сборки многоцелевого проекта.

Я думаю, что NuGet следует использовать специальный случай GeneratePackageOnBuild, чтобы одноцелевой проект сворачивался в текущую сборку, в которой уже разрешены ссылки.

Это можно обойти, добавив Directory.Build.props для вашего решения с этим свойством:

<Project>
 <PropertyGroup>
  <AddSyntheticProjectReferencesForSolutionDependencies>false</AddSyntheticProjectReferencesForSolutionDependencies>
 </PropertyGroup>
</Project>

Поскольку сборка из Visual Studio работает нормально и не приводит к ошибке, я предполагаю, что это потому, что у нее другой способ вызова всего этого?

Это можно обойти, добавив Directory.Build.props для вашего решения с этим свойством:

Обходной путь, который я придумал, который, кажется, работает, заключался в том, чтобы переключиться на ProjectReference с
Набор ReferenceOutputAssembly="false" и PrivateAssets="All" .

Я думаю, что NuGet следует использовать специальный случай GeneratePackageOnBuild, чтобы одноцелевой проект сворачивался в текущую сборку, в которой уже разрешены ссылки.

Я мог неправильно понять, что вы здесь говорите, но проблема все еще возникает, когда ClassLibrary1 является многоцелевым.

Поскольку сборка из Visual Studio работает нормально и не приводит к ошибке, я предполагаю, что это потому, что у нее другой способ вызова всего этого?

Да, к сожалению. VS создает проекты в решении, используя механизм, который отличается от обработки решений MSBuild.

Обходной путь, который я придумал, который, кажется, работает, заключался в том, чтобы переключиться на ProjectReference с
Набор ReferenceOutputAssembly="false" и PrivateAssets="All" .

Да, если это работает для вас, я бы предпочел это зависимости от решения — это понятнее со стороны MSBuild.

FWIW, у меня было 2 ссылки на один и тот же проект в решении. Открытие файла csproj в текстовом редакторе показало, что (Visual Studio этого не сделала, равно как и «удалить ссылку на проект»> «добавить ссылку на проект»).

У 2 ссылок были разные гиды, 1 из них был неправильным.

У меня была такая же ошибка, и она чем-то похожа на @sebashek , у меня было две идентичные ссылки на проекты, перечисленные в одном файле проекта. Удаление одной из ссылок устранило проблему.

@rainersigwald Я вижу, что у этого еще нет вехи. Есть планы обратиться в какой-то момент?

Я была такая же проблема. Когда я модифицировал проект и изменил имя его сборки, проект NUnitTest, ссылающийся на измененный проект, больше не мог собираться. Другие проекты, ссылающиеся на измененный проект, не были затронуты.

Я заметил, что эта ошибка возникла исключительно из-за AssemblyName измененного проекта. Когда я удалил пробел, проект NUnit снова начал работать.

Эта ошибка в основном не позволяет мне иметь пробел в имени любой сборки, которая имеет модульный тест.

обходной путь : переименовать сборку и удалить пробелы

я получаю эту ошибку в Visual Studio 2019, используя решение с сочетанием многоцелевых файлов csproj в старом и новом стилях.

не уверен, куда идти отсюда.

Не уверен, что это связано. Но я пришел сюда из-за ошибки, проверяя свой csporj, я заметил, что каким-то образом дважды включил одну и ту же ссылку на проект! После удаления дубликата моя ошибка исчезла. Так что по крайней мере есть больше причин, по которым вы можете получить эту ошибку

Это очень проблематично для проектов CMake, которые используют include_external_msproject() для добавления созданных вручную многоцелевых проектов C#. Обходной путь в этом случае не работает.

У меня была такая же двойная ссылка на проект в csproj, как и у других, удаление которой исправило это.

Была ли эта страница полезной?

0 / 5 — 0 рейтинги

Background

I had been struggling with the error «MSB4057: The target Package does ont exist in project» and found many articles on how to fix it. However, unfortunately, none of them helped me.  So, I took a step back and evaluated the projects closely. In our shop, we work with branching. The issue was that the same project in one branch worked (when MSDeploy was executed), another did not. When I compared the projects, I found this one entry (see below) was missing in the project file that was throwing the exception. When I would add it in the project (that was throwing the exception), MSDeploy worked, (for confirmation) when I removed it, it failed again.

Posting in hopes to help someone that does not have a working project.

$(MSBuildExtensionsPath32)MicrosoftVisualStudiov$(VisualStudioVersion)

Using the Code

Entering the following line within the project fixed the issue. 

$(MSBuildExtensionsPath32)MicrosoftVisualStudiov$(VisualStudioVersion)

The full entry that you use to paste into your project file looks like the following. Please be aware that all configurations should be researched for your particular project. I added a few additional articles to review in order to understand the entry.

<Import Project="$(VSToolsPath)WebApplicationsMicrosoft.WebApplication.targets" 
Condition="'$(VSToolsPath)' != ''" />

Points of Interest

The purpose for this entry is to help project compatibility when opening a project in later versions of Visual Studio.

Other articles to better understand the entry:

  • https://blogs.msdn.microsoft.com/webdev/2012/08/21/visual-studio-project-compatibility-and-visualstudioversion/
  • http://sedodream.com/PermaLink,guid,a5894bad-f2a1-441a-a5b2-74f16c6cf8aa.aspx

This member has not yet provided a Biography. Assume it’s interesting and varied, and probably something to do with programming.

This issue might occur when building .NET projects via continuous integration in Azure DevOps as well as when building from Visual Studio after upgrading the version of Visual Studio. To fix the error you may need to rebuild the project or add the rebuild in MSBuild command (If you are using MSBuild)

The target “Build” does not exist in the project. (MSB4057)

The target “Package” does not exist in the project. (MSB4057)

There are multiple solutions for this issue as listed below, you can use any of the ones listed below

Solution 1: if it’s Project is not found ,then add a Rebuild to MSBuild as shown below

 "msbuild.exe MySolution.sln /t:Project1:Rebuild;Project2:Rebuild;Project3:Rebuild /p:Configuration=Release /p:DebugType=None /p:OutputPath="C:UsersmyuserDesktopBuild""

Solution 2: Deleting the .vs folder has resolved this issue for the users who were using VS2017 or later

Solution 3: If you are facing this issue in Azure DevOps, use Visual Studio Build instead of MSBuild

Tags: MSB4057target Package

You may also like…

bording

Solution dependency leads to error MSB4057: The target «GetTargetPath» does not exist in the project

There is a problem with solution dependencies that I believe was introduced with MSBuild 15.9, and is also a problem with 16.0.

The following scenario causes the problem;

  • There is a project that has <GeneratePackageOnBuild>true</GeneratePackageOnBuild> set
  • It has a solution dependency on a second project, and that project is multi-targeted.

Steps to reproduce

Build the attached project with MSBuild.exe or dotnet build: GetTargetPathRepro.zip

Expected behavior

The solution should compile without errors.

Actual behavior

The following error occurs:

"C:UsersBrandonsourcereposGetTargetPathReproGetTargetPathRepro.sln" (default target) (1:2) ->
"C:UsersBrandonsourcereposGetTargetPathReproClassLibrary1ClassLibrary1.csproj.metaproj" (default target) (4) ->
"C:UsersBrandonsourcereposGetTargetPathReproClassLibrary1ClassLibrary1.csproj" (default target) (2:6) ->
"C:UsersBrandonsourcereposGetTargetPathReproClassLibrary1ClassLibrary1.csproj" (_GetFrameworkAssemblyReferences target) (2:10) ->
"C:UsersBrandonsourcereposGetTargetPathReproClassLibrary2ClassLibrary2.csproj" (GetTargetPath target) (3:15) ->
  C:UsersBrandonsourcereposGetTargetPathReproClassLibrary2ClassLibrary2.csproj : error MSB4057: The target "GetTargetPath" does not exist in the project.

    0 Warning(s)
    1 Error(s)

Environment data

It repros with MSBuild 15.9.21.664 and 16.0.461.62831.
It also repros with .NET Core SDK 2.2.106 and 3.0.100-preview3-010431

I believe it worked fine before MSBuild 15.9, but I don’t know an exact version.

rainersigwald

This is fairly involved. It’s related to 3258497, which was in 15.8.

NuGet packaging calls _GetFrameworkAssemblyReferences which builds the current project (ClassLibrary1) with a specified TargetFramework and BuildProjectReferences = false. That is a distinct build from the «real» build of that project, so it creates a new project instance. That instance then tries to ResolveProjectReferences, which fails because when BuildProjectReferences != true, it calls GetTargetPath instead of the default target. That then fails, because GetTargetPath isn’t defined for the outer build of a multitargeted project.

I think NuGet should special case the GeneratePackageOnBuild case for a single-targeted project to collapse to the current build, which already has references resolved.

This can be worked around by adding a Directory.Build.props for your solution with this property:

<Project>
 <PropertyGroup>
  <AddSyntheticProjectReferencesForSolutionDependencies>false</AddSyntheticProjectReferencesForSolutionDependencies>
 </PropertyGroup>
</Project>

bording

Since building from Visual Studio seems work fine and not result in an error, I assume that’s because it has a different way of invoking all of this?

This can be worked around by adding a Directory.Build.props for your solution with this property:

The workaround I came up with that seems to be working was to switch to a ProjectReference with
ReferenceOutputAssembly="false" and PrivateAssets="All" set.

bording

I think NuGet should special case the GeneratePackageOnBuild case for a single-targeted project to collapse to the current build, which already has references resolved.

I could be misunderstanding what you’re saying here, but the problem still occurs when ClassLibrary1 is multi-targeted a well.

rainersigwald

Since building from Visual Studio seems work fine and not result in an error, I assume that’s because it has a different way of invoking all of this?

Yes, unfortunately. VS builds projects in a solution using a pretty different mechanism from MSBuild’s solution handling.

The workaround I came up with that seems to be working was to switch to a ProjectReference with
ReferenceOutputAssembly="false" and PrivateAssets="All" set.

Yeah, if that works for you I’d prefer it over a solution dependency—it’s clearer from the MSBuild side.

sebashek

FWIW, I had 2 references to the same project within the solution. Opening the csproj file with a text editor indicated that (Visual Studio did not, neither did a ‘remove project reference’ > ‘add project reference’).

The 2 references had different guids, 1 of them was the incorrect one.

matiasdd

I had the same error and somewhat similar to @sebashek, I had two identical project references listed in a single project file. Removing one of the references fixed the issue.

bording

@rainersigwald I see this still has no milestone. Any plans to address at some point?

bizzbizz

I had the same issue. When I modified a project and changed its assembly name, an NUnitTest project referencing the modified project couldn’t build anymore. Other projects referencing the modified project wasn’t affected.

I noticed that this error was purely because of a space in the middle of the new AssemblyName of the modified project. When I removed the space NUnit project started working again.

This bug is basically preventing me from having a space in name of any assembly which has a unit test.

workaround: rename assembly and remove spaces

coderb

i’m getting this error in visual studio 2019 using a solution with a mix of old-style and new style multi-targeted csproj files.

not sure where to go from here.

jbennink

Not sure if this is related But I came here for the error, whil inspecting my csporj I noticed I had somehow included the same projectreference twice! After removing the duplicate my error went away. So at least there are more reasons that you can get this error

rokups

This is very problematic for CMake projects that use include_external_msproject() to add manually crafted multi-target C# projects. Workaround does not work in this case.

Ian1971

I had the same double project reference in the csproj as others, removing that fixed it.

NorbertNemec

@rokups — did you find a solution for the problem with include_external_msproject()? I seem to be stumbling over the same issue.

rokups

I do not remember. I am not dealing with this issue any more, but i can not find any relevant commits from the time of my post. Not sure if this happened in some experimental branch that i later scrapped… Sorry for being useless :|

NorbertNemec

After long struggles with the problem using include_external_msproject() I finally found an applicable workaround on wixtoolset/issues#5705:

  <Target Name="GetTargetPath" Returns="@(_FakeOutputPath)">
    <ItemGroup>
      <_FakeOutputPath Include="$(MSBuildProjectDirectory)$(PackageOutputPath)$(AssemblyName).dll" />
    </ItemGroup>
  </Target>

benmccallum

I seemed to get this after changing TargetFramework —> TargetFrameworks. The project I did this in started failing to build, but only in builds with other projects that depended on it (worked when I built it by itself). In the end I only needed one target framework so dropped the s again and that seemed to force VS to re-evaluate something that no amount of cleaning/rebuilding or opening/closing VS could solve. 🤷🏻‍♂️

ghidalgo3

kwaazaar

I added a comment to your report @ghidalgo3. It’s too complicated to create a simple repro though.

TheRealAyCe

I had the same issue. When I modified a project and changed its assembly name, an NUnitTest project referencing the modified project couldn’t build anymore. Other projects referencing the modified project wasn’t affected.

I noticed that this error was purely because of a space in the middle of the new AssemblyName of the modified project. When I removed the space NUnit project started working again.

This bug is basically preventing me from having a space in name of any assembly which has a unit test.

workaround: rename assembly and remove spaces

This was the fix for me, using xUnit. My Test assembly was referencing several projects, and the problems were only with the ones that had spaces in them, but I never would have thought that this sort of thing would still cause problems in 2022.

dotMorten

For me this issue got introduced when I started setting TargetPlatformMinVersion in the UWP project, because I wanted a smaller min-version but wanted to use the newer SDK. Only happens to the project referencing the multi-targeted project (which have the same min/max versions for UWP).
image

Понравилась статья? Поделить с друзьями:
  • Error msb4057 the target build does not exist in the project
  • Error msb4025 не удалось загрузить файл проекта
  • Error msb4019 импортированный проект c microsoft cpp default props не обнаружен
  • Error msb4018 непредвиденная ошибка при выполнении задачи resolvepackageassets
  • Error msb4018 the vcmessage task failed unexpectedly