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.
- Create a new C# console application
- Add a reference to the
NuGet.Core
NuGet package - Use the PackageRepositoryFactory to connect to your feed
- Search with an empty string
- Save the package stream.
- Download nuget.exe to c:\nuget\nuget.exe
- 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();
}
}
}