Downloading all NuGet packages

Bulk downloading NuGet packages from a NuGet server in only a few lines of code.

Today's fun task was to download all of the Nuget packages from our internal NuGet server and push them up to our new Nexus OSS environment. Since I didn't feel like doing clicking through each one and downloading all of the versions manually I wanted an automated way of doing it. Turns out, it's pretty easy. I have used this with both an authenticated feed in TFS and an unauthenticated feed withour older NuGet gallery server.

  1. Create a new C# console application
  2. Add a reference to the NuGet.Core NuGet package
  3. Use the PackageRepositoryFactory to connect to your feed
  4. Search with an empty string
  5. Save the package stream.
  6. Download nuget.exe to c:\nuget\nuget.exe
  7. Run c:\nuget\nuget.exe push c:\packages\*.nupkg -source <new nuget url> -apikey <your api key>

Here's my entire application (program.cs) code. Note, I already had a Packages folder on my C drive

using System;
using System.IO;
using NuGet;

namespace NugetDownloader
{
    class Program
    {
        static void Main(string[] args)
        {
            var packageId = string.Empty; //Don't filter the search
            var path = "c:\\packages"; //Output folder
            var repositoryUrl = "<<NUGET SERVER>/api/v2"; //Url of the V2 nuget api
            
            var repository = PackageRepositoryFactory.Default.CreateRepository(repositoryUrl);
            var packages = repository.Search(packageId, true);
            var packageManager = new PackageManager(repository, path);

            foreach (var package in packages)
            {
                var fileName = Path.Combine(path, package.Id + "-" + package.Version.ToFullString() + ".nupkg";
                Console.WriteLine(fileName);

                using (var stream = package.GetStream())
                {
                    File.WriteAllBytes(fileName), stream.ReadAllBytes());
                }
            }
            
            Console.WriteLine("Done");
            Console.ReadLine();
        }
    }
}