Error netsdk1004 assets file

This repository contains .NET Documentation. Contribute to dotnet/docs development by creating an account on GitHub.

Permalink

Cannot retrieve contributors at this time

title description ms.topic ms.date f1_keywords

NETSDK1004: Assets file not found

Learn about .NET SDK error NETSDK1004, which occurs when the project.assets.json file is not found.

error-reference

01/29/2021

NETSDK1004

NETSDK1004: Assets file not found

This article applies to: ✔️ .NET Core 2.1.100 SDK and later versions

NuGet writes a file named project.assets.json in the obj folder, and the .NET SDK uses it to get information about packages to pass into the compiler. This error occurs when the assets file project.assets.json is not found during build. The full error message is similar to the following example:

NETSDK1004: Assets file ‘C:pathtoproject.assets.json’ not found. Run a NuGet package restore to generate this file.

Here are some possible causes of the error:

  • You are running the dotnet build command from a directory path that contains a % character. To resolve the error, remove the % from the folder name, and rerun dotnet build.
  • A change to the project file wasn’t automatically detected and restored by the project system. To resolve the error, open a command prompt and run dotnet restore on the project.
  • A project was restored separately by an older version of Nuget.exe. To resolve the error, open a command prompt and run dotnet restore on the project.
  • An earlier error, such as NETSDK1045 (the version of the SDK you’re using doesn’t support the project’s target framework), prevented NuGet from creating the project assets file. To resolve the NETSDK1004 error, resolve the earlier error, and then run dotnet restore on the project.
  • App Center CI is building a project that has an external assembly that is not in NuGet. To resolve the error, use a NuGet package for the assembly.
  • You added a solution folder in Visual Studio with a name that starts with a period. To resolve the error, remove the leading period from the folder name.
  • You have a source in the <packageSources> section in the NuGet.Config file with a path that doesn’t exist. To resolve the error, edit the NuGet.Config file to correct the package source path.

I’m trying to use nopCommerce(Which is written in .NET Core) but when I want to run the project I face 52 Errors telling me Run a nuget package restore

Assets file ~objproject.assets.json’ not found. Run a NuGet package restore to generate this file. Nop.Web.MVC.Testsote

when I use the right click on the solution and selecting Restore Nuget Packages I get this message:

All packages are already installed and there is nothing to restore.

but those 52 Errors are still there and in Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution there is nothing installed on the solution,also I Recently updated my VS2017 to 15.5.4

xpt's user avatar

xpt

18.8k35 gold badges114 silver badges205 bronze badges

asked Jan 25, 2018 at 10:04

NeverTrust's user avatar

10

To fix this error from Tools > NuGet Package Manager > Package Manager Console simply run:

dotnet restore

The error occurs because the dotnet cli does not create the all of the required files initially. Doing dotnet restore adds the required files.

Matteo Migliore's user avatar

answered Jan 25, 2018 at 10:35

Mostafa Bouzari's user avatar

Mostafa BouzariMostafa Bouzari

8,5762 gold badges14 silver badges19 bronze badges

18

In my case the error was the GIT repository. It had spaces in the name, making my project unable to restore

If this is your issue, just rename the GIT repository when you clone

git clone http://Your%20Project%20With%20Spaces newprojectname

answered May 2, 2018 at 20:07

Sebastian Castaldi's user avatar

6

In case when ‘dotnet restore’ not works, following steps may help:

  1. Visual Studio >> Tools >> Options >> Nuget Manager >> Package Sources
  2. Unchecked any third party package sources.
  3. Rebuild solution.

answered Nov 19, 2018 at 8:23

prisan's user avatar

prisanprisan

1,19311 silver badges9 bronze badges

10

To those with the same issue as me in Azure DevOps / VSTS environment encountering a similar message:

C:Program Filesdotnetsdk2.2.104SdksMicrosoft.NET.SdktargetsMicrosoft.PackageDependencyResolution.targets(208,5): Error NETSDK1004: Assets file ‘…objproject.assets.json’ not found. Run a NuGet package restore to generate this file

Add /t:Restore to your MSBuild Arguments in Build Solution.

Uwe Keim's user avatar

Uwe Keim

39k56 gold badges175 silver badges289 bronze badges

answered Apr 17, 2019 at 18:31

taylorswiftfan's user avatar

2

Closing and re-opening Visual Studio solved this issue for me, once I had made sure the NuGet packages had been restored as per other answers posted here.

Edit: Sometimes just trying to build again fixes the problem.

answered Jun 13, 2018 at 9:21

OutstandingBill's user avatar

5

For me when i did — dotnet restore still error was occurring.

I went to

1 Tool -> NuGet Package Maneger -> Package Manager settings -> click on «Clear all NuGet Cache(s)»

2 dotnet restore

resolved issues.

Homer's user avatar

Homer

7,56214 gold badges69 silver badges109 bronze badges

answered Mar 13, 2019 at 15:58

Speed's user avatar

SpeedSpeed

3471 gold badge3 silver badges12 bronze badges

3

In visual studio 2017 please do following steps:

1) select Tool=>Options=>NuGet Package Manager=> Package Sources then uncheck Microsoft Visual Studio Offline Packages Option.
enter image description here

2) now open Tool=>NuGet Package Maneger=>Package Manager Console.
3) execute command in PM>dotnet restore.

Hope its working…

answered Sep 5, 2018 at 7:10

Manoj Gupta's user avatar

Manoj GuptaManoj Gupta

4474 silver badges9 bronze badges

1

It was mentioned earlier but I just wanted to re-emphasize the importance of not have space anywhere in your pathing! This is what was getting me. You’ve been warned.

answered Jul 22, 2020 at 0:57

Mike Homol's user avatar

Mike HomolMike Homol

4815 silver badges18 bronze badges

1

If this error occurs as part of a build in Azure DevOps (TFS) and your build already has a NuGet restore task, this error may indicate the NuGet restore task was not able to restore all packages, especially if you use a custom package source (such as an internal NuGet server). Adding /t:Restore;Build to the MSBuild Arguments seems to be one way to resolve the error, but this asks MSBuild to perform an additional NuGet restore operation. I believe this succeeds because MSBuild uses the custom package source configured in Visual Studio. A preferable solution is to fix the NuGet restore task.

To configure a custom package source for the NuGet restore task:

  1. Create a NuGet.config file that lists all of the package sources (Microsoft Visual Studio Offline Packages, nuget.org, and your custom package source) and add it to source control.
  2. In the Nuget restore task under Feeds to use: select the option Feeds in my NuGet.config.
  3. Provide the path to NuGet.config.
  4. Remove the /t:Restore;Build option from the MSBuild task.

Additional information is available here.

answered Mar 24, 2020 at 2:23

Jeremiah Mercier's user avatar

For me I upgraded NuGet.exe from 3.4 to 4.9 because 3.4 doesn’t understand how to restore packages for .NET Core.

For details please see dotnet restore vs. nuget restore with teamcity

answered Apr 26, 2019 at 17:53

user8128167's user avatar

user8128167user8128167

6,6166 gold badges63 silver badges79 bronze badges

1

You will get required packages from «https://api.nuget.org/v3/index.json». Add this in Package Resources. Also make sure other packages are unchecked for time being. And Click Restore Nuget Package on Solution Explorer enter image description here

answered Aug 13, 2020 at 13:46

Yogesh Dangre's user avatar

Select Tools > NuGet Package Manager > Package Manager Console

And then Run:

dotnet restore <project or solution name>

answered Nov 19, 2018 at 19:29

Andre Mesquita's user avatar

Solved by adding /t:Restore;Build to MSBuild Arguments

answered Nov 27, 2019 at 12:09

Abdulsamet ILERI's user avatar

2

Nothing above worked for me. But simply deleting all ‘bin’ and ‘obj’ folders did the trick.

answered May 13, 2019 at 13:21

alexbk66's user avatar

alexbk66alexbk66

3331 gold badge3 silver badges12 bronze badges

1

You can go for : Tools > NuGet Package Manager > Package Manager Console

And then Run:

dotnet restore

answered May 29, 2020 at 17:30

seven's user avatar

sevenseven

871 silver badge4 bronze badges

little late to the answer but seems this will add value. Looking at the error — it seems to occur in CI/CD pipeline.

Just running «dotnet build» will be sufficient enough.

dotnet build

dotnet build runs the «restore» by default.

answered Jun 8, 2018 at 10:05

Sunny Sharma's user avatar

Sunny SharmaSunny Sharma

4,4735 gold badges34 silver badges73 bronze badges

1

I lost several hours on this error in Azure DevOps when I set the ‘Visual Studio Build’ task in a build pipeline to build an individual project in my solution, rather than the whole solution.

Doing that means that DevOps either doesn’t build any (or possibly some, I’m not sure which) of the projects referenced by the project you’ve targeted for the build, and therefore those projects won’t have their project.json.asset files generated, which then causes this issue.

The solution for me was to swap from using the VS Build task to the MSBuild task. Using the MSBuild task for an individual project correctly builds any projects referenced by the project you’re building and eliminates this error.

answered May 20, 2019 at 20:57

tomRedox's user avatar

tomRedoxtomRedox

26.8k23 gold badges118 silver badges149 bronze badges

This problem happening when your build tool is not set to do restore on projects set to use PackageReference vs packages.config and mostly affect Net Core and Netstandard new style projects.

When you open Visual Studio and build, it resolves this for you. But if you use automation, CLI tools, you see this issue.

Many solutions are offered here. But all you need to remember, you need to force restore. In some instances you use dotnet restore before build. If you build using MsBuild just add /t:Restore switch to your command.

Bottom line, you need to see why restoring can’t be activated. Either bad nuget source or missing restore action, or outdated nuget.exe, or all of the above.

answered Oct 24, 2019 at 20:40

T.S.'s user avatar

T.S.T.S.

17.6k11 gold badges57 silver badges78 bronze badges

1

If simply restoring NuGet packages does not work make sure in Tools -> Options -> NuGet Package Manager -> General under Package Restore that the «Allow NuGet to download missing packages» is checked.

Then Restore NuGet Packages again OR just REBUILD after deleting obj and bin folders.

Nick Kovalsky's user avatar

answered Jul 4, 2018 at 15:09

NexX's user avatar

NexXNexX

1931 silver badge13 bronze badges

0

run your VS as administrator after that in package manager console run dotnet restore.

answered Sep 30, 2018 at 23:24

Lucas Brito's user avatar

1

When using VSTS, check your global.json file. I had entered the sdk version as just «2.2» which caused a parse error (but not when building locally). Adding the full version, «2.2.104» solved the problem.

answered Apr 5, 2019 at 21:36

Rob Minnis's user avatar

I have same problem and dotnet resotre not work for me. I Install this component:

enter image description here

and the run dotnet resotre and the problem has solved.

answered Feb 26, 2022 at 9:42

Arian's user avatar

ArianArian

12.9k63 gold badges174 silver badges290 bronze badges

In my case, I had the following added to my *.csproj files to fully remove obj and bin folders on ‘Clean’. Apparently, it was the culprit. Got rid of that and viola, all started to work again. Now I’m using the «Clean Bin» extension instead. Hope this might help anyone who is running into this issue, and none of the mentioned fixes works.

<Target Name="SuperClean" AfterTargets="Clean">
    <!-- Remove obj folder -->
    <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
    <!-- Remove bin folder -->
    <RemoveDir Directories="$(BaseOutputPath)" />
</Target>    

answered Sep 19, 2021 at 9:02

Ε Г И І И О's user avatar

Ε Г И І И ОΕ Г И І И О

10.6k1 gold badge45 silver badges58 bronze badges

Another one, if by any chance you’re using Dropbox, check for Conflicted in file names, do a search in your repo and delete all those conflicted files.

This may have happened if you have moved the files around.

answered Feb 13, 2019 at 3:50

Jose A's user avatar

Jose AJose A

9,61110 gold badges72 silver badges103 bronze badges

Cause of this defect: you have to remove the injected Nuget in file explorer.
Solution: Once you remove that Nuget in your system, then remove from following location.
select Tool=>Options=>NuGet Package Manager=> Package Sources then uncheck Microsoft Visual Studio Offline Packages Option

answered Feb 14, 2019 at 10:18

balaji s's user avatar

In my case I had a problem with the Available Package Sources. I had move the local nuget repository folder to a new path but I did not update it in the Nuget Available Package Sources. When I’ve correct the path issue, update it in the Available Package Sources and after that everything (nuget restor, etc) was working fine.

answered Aug 28, 2019 at 16:57

user11990436's user avatar

Very weird experience I have encountered!

I had cloned with GIT bash and GIT cmd-Line earlier, I encountered the above issues.

Later, I cloned with Tortoise-GIT and everything worked as expected.

May be this is a crazy answer, but trying with this once may save your time!

answered Jan 31, 2020 at 10:09

Bikram's user avatar

BikramBikram

4636 silver badges16 bronze badges

Seen this after adding a WinForms Core 3.1 project (from project templates) on VS-2019 vs 16.4.0 and trying to run it out of the box. Clean or Rebuild the entire solution did not work.

I just reloaded my solution.. that is File/Close Solution and then reopening it and rebuilding it solved the problem.

answered Feb 1, 2020 at 2:05

Goodies's user avatar

GoodiesGoodies

1,89121 silver badges25 bronze badges

0

For me it turned out to be a nuget source credentials problem. I had recently changed my password for accessing a nexus server and visual studio was still using the old password when trying to access a nuget on that server through the windows credential manager. To fix it, I had to delete the entry for those outdated credentials in the credential manager and after, when I did a nuget restore, it prompted me for a password letting me enter the new password, which got saved in the credential manager again. You can access the credential manager from the cmd line using CmdKey.exe.

answered Feb 4, 2020 at 10:58

J. Volkya's user avatar

J. VolkyaJ. Volkya

9933 gold badges14 silver badges32 bronze badges

What Does the NETSDK1004 Message Mean?

Error NETSDK1004: "Assets file 'C:project.assets.json' not found. Run a NuGet package restore to generate this file.

The NETSDK1004 compile error occurred when I was refactoring the CSPROJ files within my solution. In the process, I created a Directory.Build.props file, copying out the Project root element from the CSPROJ file including the SDK.  (In my case, I happened to be moving out C# 8.0’s Nullable element – enable.)  The result was the above compile error.

The SDK XML Attribute was the Mistake

The SDK attribute causes the above error along with multiple occurrences of this associated warning:

warning MSB4011: "C:Program Filesdotnetsdk3.1.100SdksMicrosoft.NET.SdkSdkSdk.targets" cannot be imported again. It was already imported at "…Directory.Build.props". This is most likely a build authoring error. This subsequent import will be ignored.

Pull out the SDK attribute and the error goes away. Here’s the corrected Directory.Build.props file:

<Project>
     <PropertyGroup>
         <Nullable>enable</Nullable>
         <TargtFramework>NetCoreApp3.1</TargtFramework>
     </PropertyGroup>
</Project>

Note: This example also pulls out the TargetFramework element.

If you are working with a solution and all projects are C# 8.0, I recommend you refactor out the Nullable attribute into a Directory.Build.props file as shown in this example, rather than individually edit it in all the CSPROJ files independently.

Want More?

Check out our blog How to Publish NuGets with Azure DevOps for more information on NuGet packages! Microsoft also offers documentation on the NETSDK1004 error.

Does Your Organization Need a Custom Solution?

Let’s chat about how we can help you achieve excellence on your next project!

Содержание

  1. Устранение ошибок при восстановлении пакетов
  2. Быстрое решение для пользователей Visual Studio
  3. Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере
  4. Файл ресурсов project.assets.json не найден
  5. Необходимо восстановить один пакет NuGet или несколько, но это не удалось выполнить, так как не было получено согласие
  6. Другие потенциальные условия
  7. Troubleshooting package restore errors
  8. Quick solution for Visual Studio users
  9. This project references NuGet package(s) that are missing on this computer
  10. Assets file project.assets.json not found
  11. One or more NuGet packages need to be restored but couldn’t be because consent has not been granted
  12. Other potential conditions
  13. Quick Fix for the NETSDK1004 Compile Error
  14. What Does the NETSDK1004 Message Mean?
  15. The SDK XML Attribute was the Mistake
  16. Want More?
  17. Does Your Organization Need a Custom Solution?
  18. Asset file — project.assets.json not found #4380
  19. Comments
  20. dotnet Info:

Устранение ошибок при восстановлении пакетов

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

Функция восстановления пакетов пытается установить все зависимости пакетов в правильном состоянии с учетом ссылок на пакет в файле проекта ( .csproj) или файле packages.config. (В Visual Studio ссылки отображаются в обозревателе решений в узле Зависимости NuGet или Ссылки.) См. о восстановлении пакетов. Если пакет ссылается на файл проекта( .csproj) или если файл packages.config неправильный (не соответствует требуемому состоянию после восстановления пакета), необходимо установить или обновить пакеты. Не используйте вместо этого функцию восстановления пакетов.

Если приведенные здесь инструкции не работают, сообщите о проблеме на GitHub, чтобы мы могли тщательнее изучить ваш случай. Не используйте элемент управления «Была ли эта страница полезной?», который может отображаться на этой странице, так как это не позволяет нам связаться с вами для получения дополнительной информации.

Быстрое решение для пользователей Visual Studio

Если вы используете Visual Studio, сначала включите восстановление пакета, как описано ниже. В противном случае перейдите к приведенным далее разделам.

  1. Выберите команду Средства > Диспетчер пакетов NuGet > Параметры диспетчера пакетов.
  2. Задайте оба параметра в разделе Восстановление пакета.
  3. Нажмите кнопку ОК.
  4. Повторите сборку проекта.

Эти параметры также можно изменить в файле NuGet.Config ; см раздел о согласии. Для достаточно ранних проектов, использующих встроенную в MSBuild функцию восстановление пакетов, возможно, потребуется перейти на автоматическое восстановление пакетов.

Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере

Полное сообщение об ошибке.

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

  • При использовании формата управления PackageReference эта ошибка может быть следствием миграции packages.config в PackageReference, и это необходимо вручную удалить из файла проекта.
  • Если используется файл packages.config эта ошибка означает, что пакет не установлен в папке packages в корне решения.

Обычно такая ситуация возникает при получении исходного кода проекта из системы управления версиями или другого скачанного файла. Пакеты обычно исключаются из системы управления версиями или скачиваемых файлов, так как их можно восстановить из веб-каналов пакета, например nuget.org (см. раздел Пакеты и система управления версиями). Их включение приведет к раздуванию репозитория или созданию слишком больших ZIP-файлов.

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

Для восстановления пакетов используйте один из следующих методов.

После восстановления пакет должен присутствовать в папке global-packages. В проектах, использующих формат PackageReference, в процессе восстановления повторно создается файл obj/project.assets.json , а в проектах, использующих файл packages.config , пакет должен появиться в папке packages . Теперь сборка проекта должна пройти без ошибок. В противном случае сообщите о проблеме на GitHub, чтобы мы могли связаться с вами.

Файл ресурсов project.assets.json не найден

Полное сообщение об ошибке.

Если используется формат управления PackageReference, который проверяет, установлены ли на компьютере все необходимые пакеты, в файле project.assets.json определена схема зависимостей проекта. Этот файл создается динамически во время восстановления пакета. Поэтому он обычно не добавляется в систему управления версиями. В результате эта ошибка возникает при попытке выполнить сборку проекта с помощью такого средства, как msbuild , которое не восстанавливает пакеты автоматически.

В этом случае запустите msbuild -t:restore и затем msbuild или используйте dotnet build (при этом пакеты восстанавливаются автоматически). Кроме того, вы можете использовать любой из методов восстановления пакетов, описанных в предыдущем разделе.

Необходимо восстановить один пакет NuGet или несколько, но это не удалось выполнить, так как не было получено согласие

Полное сообщение об ошибке.

Эта ошибка означает, что восстановление пакета отключено в конфигурации NuGet.

Вы можете изменить подходящие параметры в Visual Studio, как описано выше в разделе Быстрое решение для пользователей Visual Studio.

Можно также изменить эти параметры напрямую в соответствующем файле nuget.config (обычно это %AppData%NuGetNuGet.Config в Windows и

/.nuget/NuGet/NuGet.Config в Mac и Linux). Убедитесь, что для ключей enabled и automatic в разделе packageRestore задано значение True.

При изменении параметров packageRestore прямо в nuget.config нужно перезапустить Visual Studio, чтобы диалоговое окно параметров отображало текущие значения.

Другие потенциальные условия

Могут возникнуть ошибки сборки, связанные с отсутствием файлов и указывающие, что для их скачивания следует использовать NuGet restore. Но при выполнении команды restore может появиться сообщение «Все пакеты уже установлены, и элементы для восстановления отсутствуют». В этом случае удалите папку packages (при использовании packages.config ) или файл obj/project.assets.json (при использовании PackageReference) и выполните команду restore еще раз. Если это не помогло решить проблему, очистите папку global-packages и кэш, выполнив в окне командной строки команду nuget locals all -clear или dotnet nuget locals all —clear . Дополнительные сведения см. в статье Управление папкой установки глобальных пакетов, кэшем и временными папками.

При получении проекта из системы управления версиями папки вашего проекта могут быть сделаны доступными только для чтения. Измените разрешения для папок и попробуйте восстановить пакеты еще раз.

Возможно, вы используете старую версию NuGet. Ознакомьтесь с последними рекомендуемыми версиями на странице nuget.org/downloads. Для Visual Studio 2015 рекомендуется версия 3.6.0.

При возникновении других проблем сообщите о них на GitHub, чтобы мы могли получить у вас дополнительные сведения.

Источник

Troubleshooting package restore errors

This article focuses on common errors when restoring packages and steps to resolve them.

Package Restore tries to install all package dependencies to the correct state matching the package references in your project file (.csproj) or your packages.config file. (In Visual Studio, the references appear in Solution Explorer under the Dependencies NuGet or the References node.) To follow the required steps to restore packages, see Restore packages. If the package references in your project file (.csproj) or your packages.config file are incorrect (they do not match your desired state following Package Restore), then you need to either install or update packages instead of using Package Restore.

If the instructions here do not work for you, please file an issue on GitHub so that we can examine your scenario more carefully. Do not use the «Is this page helpful?» control that may appear on this page because it doesn’t give us the ability to contact you for more information.

Quick solution for Visual Studio users

If you’re using Visual Studio, first enable package restore as follows. Otherwise continue to the sections that follow.

  1. Select the Tools > NuGet Package Manager > Package Manager Settings menu command.
  2. Set both options under Package Restore.
  3. Select OK.
  4. Build your project again.

These settings can also be changed in your NuGet.Config file; see the consent section. If your project is an older project that uses the MSBuild-integrated package restore, you may need to migrate to automatic package restore.

This project references NuGet package(s) that are missing on this computer

Complete error message:

This error occurs when you attempt to build a project that contains references to one or more NuGet packages, but those packages are not presently installed on the computer or in the project.

  • When using the PackageReference management format, this error might be a leftover from a packages.config to PackageReference migration and needs to be manually removed from the project file.
  • When using packages.config, the error means that the package is not installed in the packages folder at the solution root.

This situation commonly occurs when you obtain the project’s source code from source control or another download. Packages are typically omitted from source control or downloads because they can be restored from package feeds like nuget.org (see Packages and source control). Including them would otherwise bloat the repository or create unnecessarily large .zip files.

The error can also happen if your project file contains absolute paths to package locations, and you move the project.

Use one of the following methods to restore the packages:

After a successful restore, the package should be present in the global-packages folder. For projects using PackageReference, a restore should recreate the obj/project.assets.json file; for projects using packages.config , the package should appear in the project’s packages folder. The project should now build successfully. If not, file an issue on GitHub so we can follow up with you.

Assets file project.assets.json not found

Complete error message:

The project.assets.json file maintains a project’s dependency graph when using the PackageReference management format, which is used to make sure that all necessary packages are installed on the computer. Because this file is generated dynamically through package restore, it’s typically not added to source control. As a result, this error occurs when building a project with a tool such as msbuild that does not automatically restore packages.

In this case, run msbuild -t:restore followed by msbuild , or use dotnet build (which restores packages automatically). You can also use any of the package restore methods in the previous section.

One or more NuGet packages need to be restored but couldn’t be because consent has not been granted

Complete error message:

This error indicates that package restore is disabled in your NuGet configuration.

You can change the applicable settings in Visual Studio as described earlier under Quick solution for Visual Studio users.

You can also edit these settings directly in the applicable nuget.config file (typically %AppData%NuGetNuGet.Config on Windows and

/.nuget/NuGet/NuGet.Config on Mac/Linux). Make sure the enabled and automatic keys under packageRestore are set to True:

If you edit the packageRestore settings directly in nuget.config , restart Visual Studio so that the options dialog box shows the current values.

Other potential conditions

You may encounter build errors due to missing files, with a message saying to use NuGet restore to download them. However, running a restore might say, «All packages are already installed and there is nothing to restore.» In this case, delete the packages folder (when using packages.config ) or the obj/project.assets.json file (when using PackageReference) and run restore again. If the error still persists, use nuget locals all -clear or dotnet nuget locals all —clear from the command line to clear the global-packages and cache folders as described on Managing the global packages and cache folders.

When obtaining a project from source control, your project folders may be set to read-only. Change the folder permissions and try restoring packages again.

You may be using an old version of NuGet. Check nuget.org/downloads for the latest recommended versions. For Visual Studio 2015, we recommend 3.6.0.

If you encounter other problems, file an issue on GitHub so we can get more details from you.

Источник

Quick Fix for the NETSDK1004 Compile Error

What Does the NETSDK1004 Message Mean?

The NETSDK1004 compile error occurred when I was refactoring the CSPROJ files within my solution. In the process, I created a Directory.Build.props file, copying out the Project root element from the CSPROJ file including the SDK. (In my case, I happened to be moving out C# 8.0’s Nullable element – enable .) The result was the above compile error.

The SDK XML Attribute was the Mistake

The SDK attribute causes the above error along with multiple occurrences of this associated warning:

Pull out the SDK attribute and the error goes away. Here’s the corrected Directory.Build.props file:

Note: This example also pulls out the TargetFramework element.

If you are working with a solution and all projects are C# 8.0, I recommend you refactor out the Nullable attribute into a Directory.Build.props file as shown in this example, rather than individually edit it in all the CSPROJ files independently.

Want More?

Check out our blog How to Publish NuGets with Azure DevOps for more information on NuGet packages! Microsoft also offers documentation on the NETSDK1004 error.

Does Your Organization Need a Custom Solution?

Let’s chat about how we can help you achieve excellence on your next project!

Источник

Asset file — project.assets.json not found #4380

Asset file — project.assets.json not found

Following the quick start tutorials from this link: https://docs.microsoft.com/en-us/dotnet/core/

  1. Created a new console application: dotnet new console
  2. Running the application: dotnet run resulted in the following error:

C:Program Filesdotnetsdk3.1.102SdksMicrosoft.NET.SdktargetsMicrosoft.PackageDependencyResolution.targets(234,5): error NETSDK1004: Assets file ‘E:prosdonet-cli-projobjproject.assets.json’ not found. Run a NuGet package restore to generate this file. [E:csharp projectsdonet-cli-projdonet-cli-proj.csproj]
The build failed. Fix the build errors and run again.

I also tried dotnet restore but still showing the above error.

dotnet Info:

`
.NET Core SDK (reflecting any global.json):
Version: 3.1.102
Commit: 573d158fea

Runtime Environment:
OS Name: Windows
OS Version: 10.0.18362
OS Platform: Windows
RID: win10-x64
Base Path: C:Program Filesdotnetsdk3.1.102

Host (useful for support):
Version: 3.1.2
Commit: 916b5cba26

.NET Core SDKs installed:
3.0.100 [C:Program Filesdotnetsdk]
3.1.102 [C:Program Filesdotnetsdk]

.NET Core runtimes installed:
Microsoft.AspNetCore.All 2.1.13 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.All]
Microsoft.AspNetCore.App 2.1.13 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.0.0 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.1.2 [C:Program FilesdotnetsharedMicrosoft.AspNetCore.App]
Microsoft.NETCore.App 2.1.13 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 3.0.0 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.NETCore.App 3.1.2 [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
Microsoft.WindowsDesktop.App 3.0.0 [C:Program FilesdotnetsharedMicrosoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 3.1.2 [C:Program FilesdotnetsharedMicrosoft.WindowsDesktop.App]

To install additional .NET Core runtimes or SDKs:
https://aka.ms/dotnet-download
`

The text was updated successfully, but these errors were encountered:

Источник

Buy Me A Coffee

Hi!

Quick post today.
This one is to save me 30 minutes of internet search next time I face this
error.

Context:

New .Net
Core Console App.

When I
build the console app for the 1st time I got this error.

  • Error: NETSDK1004
  • Assets file ‘<Path> EventConsoleApp01objproject.assets.json’ not found.
  • Run a NuGet package restore to generate this file.
  • C:Program Filesdotnetsdk3.0.100SdksMicrosoft.NET.SdktargetsMicrosoft.PackageDependencyResolution.targets

visual studio 2019 new dotnet core console error on 1st build, cant find assets json.jpg

It’s a very
silly error. However, if you are old school, the standard methods to fix this
won’t work.

So the
right way to fix this is to open the NuGet Package Manager Console [Tools //
Nuget Package Manager / Package Manager Console] and type the command

dotnet restore

visual studio 2019 dotnet restore on nuget package manager console.jpg

Then
rebuild the project, and that’s it! The new build will restore all the package,
and also install everything necessary for a console app to run

visual studio 2019 project after dotnet restore.jpg

Happy coding!

Greetings @
Toronto

El Bruno

#c# #.net-5

Вопрос:

Я пытаюсь опубликовать свое приложение .NET 5, когда публикация с помощью целевой среды выполнения = Переносная публикация завершается успешно, при изменении целевой среды выполнения на win-x64, например, публикация завершается неудачно.

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

 C:Program Files (x86)Microsoft Visual Studio2019PreviewCommon7IDECommonExtensionsMicrosoftNuGetNuGet.targets(131,5): Error : Invalid framework identifier ''.
 

Я заметил, что «project.assets.json» создается в директории «objproject.assets.json», но похоже, что процесс сборки на самом деле ожидает, что он будет в «objpublishwin-x64project.assets.json», и его там нет. Ручное копирование файла заставляет все работать, но такой подход был бы очень утомительным.

Есть ли какая-либо конфигурация проекта, которую мне нужно изучить ? Спасибо.

Ответ №1:

Похоже, проблема была вызвана тем, что в некоторых зависимых библиотеках проектов для пути appendtargetframeworktooutput установлено значение false.

Понравилась статья? Поделить с друзьями:
  • Error net ads join returned error 255
  • Error nero express
  • Error negotiating ssl connection on fd error squid
  • Error negotiate authentication validating user
  • Error need typename before because is a dependent scope