Search code examples
c#nugetnuget-package

Push NuGet package programmatically using NuGet.Core


I'm currently packaging some files and pushing them on to a NuGet feed on one of our servers using the command line tool. Rather than using the command line tool I've set up a project using Nuget.Core and successfully managed to create a package. I'm now trying to push that package from my machine on to the NuGet feed via NuGet.Core. Using the command line tool that looks like this (and I got this working too):

nuget.exe push package.nupkg -ApiKey MYAPIKEY -Source http://nugetpackagefeedaddress

What I want to do is replicate the push function using NuGet.Core. The closest I've managed to get so far is getting two repositories from the PackageRepositoryFactory, one for the local machine path and one for the package feed and then retrieve the package from the local one and try and add it to the feed like this:

var remoteRepo = PackageRepositoryFactory.Default.CreateRepository("myNugetPackagefeedUrl");
var localRepo = PackageRepositoryFactory.Default.CreateRepository(@"locationOfLocalPackage");
var package = localRepo.FindPackagesById("packageId").First();
remoteRepo.AddPackage(package);

This code results in a NotSupportedException stating the 'Specified method is not supported'

Is it possible to push packages using NuGet.Core? and am I anywhere close to it with the above code?

Note: I'm aware I could wrap the call to nuget.exe and call that from .NET but I'd either want to package and push from NuGet.Core or do both by wrapping the calls to nuget.exe rather than half and half


Solution

  • So it turns out I was looking in the wrong place entirely. The method I wanted was PushPackage on PackageServer

    The code now looks like this

    var localRepo = PackageRepositoryFactory.Default.CreateRepository(@"locationOfLocalPackage");
    var package = localRepo.FindPackagesById("packageId").First();
    var packageFile = new FileInfo(@"packagePath");
    var size = packageFile .Length;
    var ps = new PackageServer("http://nugetpackagefeedaddress", "userAgent");
    ps.PushPackage("MYAPIKEY", package, size, 1800, false);
    

    I'm not sure what the best values for the userAgent parameter when newing up the PackageServer would be. Similarly if anyone has any advice on what the timeout or disableBuffering parameters want to be, let me know (for example is the timeout in ms, seconds etc.)

    The PushPackage method signature looks like this:

    void PackageServer.PushPackage(string apiKey, IPackage package, long packageSize, int timeout, bool disableBuffering)