Using NuGet.Core to Get the Latest Version of a Package

Add the NuGet.Core package from NuGet and you’ll be in business. We use a NuGet config-file to get the one or more repositories that you might be using and hit them one at a time.

using NuGet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.XPath;

namespace LatestVersion
{
    class PackageNotFoundException : Exception
    {
        public string PackageName { get; private set; }

        public PackageNotFoundException(string packageName) : base(String.Format("Package [{0}] not found.", packageName))
        {
            PackageName = packageName;
        }
    }

    class NuGet
    {
        string nugetConfigFilepath;

        public NuGet(string nugetConfigFilepath)
        {
            this.nugetConfigFilepath = nugetConfigFilepath;
        }

        public IEnumerable<Tuple> GetSources()
        {
            XPathNavigator nav;
            XPathDocument docNav;
            string xPath;

            docNav = new XPathDocument(nugetConfigFilepath);
            nav = docNav.CreateNavigator();
            xPath = "/configuration/packageSources/add";

            foreach (XPathNavigator xpn in nav.Select(xPath))
            {
                string name = xpn.GetAttribute("key", "");
                string uri = xpn.GetAttribute("value", "");

                yield return new Tuple(name, uri);
            }
        }

        public SemanticVersion GetLatestVersion(string packageName)
        {
            foreach (Tuple source in GetSources())
            {
                string name = source.Item1;
                string uri = source.Item2;

                IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository(uri);

                // Passing NULL for `versionSpec` will return the latest version.
                IEnumerable packagesRaw = repo.FindPackages(packageName, null, false, false);
                IList packages = packagesRaw.ToList();

                if (packages.Count == 0)
                {
                    continue;
                }

                return packages[0].Version;
            }

            throw new PackageNotFoundException(packageName);
        }
    }
}
Advertisements