Building .NET While Offline Using the Local NuGet Cache

There are plenty of times when I’m offline and want to create a new .NET application. If it’s a trivial application without NuGet packages, then I’m fine.

But usually, I need to add at least one NuGet package, now I have a problem. I’ve always found this a little strange - whenever I add a NuGet package it is downloaded to my computer, I have over 800 on the computer I’m using right now.

Why don’t the restore or build commands use the package that is cached locally. It might be to look for the newest version, but I’m offline, so I can’t get the latest version anyway. The most recent will do.

Fortunately, there is a way to get the restore and build commands to use the local cache.

Find the Local NuGet Cache

First I have to locate the local NuGet cache.

Run the following command to see where you are storing NuGet packages -

dotnet nuget locals all --list

It will show output like -

http-cache: C:\Users\bryan\AppData\Local\NuGet\v3-cache
global-packages: C:\Users\bryan\.nuget\packages\
temp: C:\Users\bryan\AppData\Local\Temp\NuGetScratch
plugins-cache: C:\Users\bryan\AppData\Local\NuGet\plugins-cache

The global-packages folder is the one you want.

Add this as a source for NuGet

NuGet can look at multiple sources for packages, by default the highest priority source is nuget.org. Take a look at the current sources by running -

dotnet nuget list source 
Registered Sources:
  1. nuget.org [Enabled]
 https://api.nuget.org/v3/index.json

You can see that nuget.org is the only source I have set. If you had Visual Studio, there would be a secondary source set up for that.

To get builds working offline, add the directory from step 1 to the list of sources.

dotnet nuget add source C:\Users\bryan\.nuget\packages\ -n local

Run the list source command again -

dotnet nuget list source 

You should see the new source -

Registered Sources:
  1. nuget.org [Enabled]
 https://api.nuget.org/v3/index.json
  2. local [Enabled]
 C:\Users\bryan\.nuget\packages\

Using add package while offline

When offline you have to specify the version of the package you want to add to the application.

For example if you want to add Microsoft.Extensions.Caching.Memory to you application, go to the directory from the first step, and check which versions of the package you have locally.

Now use this command to add the package -

dotnet add package Microsoft.Extensions.Caching.Memory --version 8.0.0

That’s it. Now I can build almost anything while offline.

comments powered by Disqus

Related