Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.5 kB
0
Indexable
Never
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace NuGetPackageManagerExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string repositoryPath = "path/to/local/repository"; // set the local repository path

            // set up the NuGet package source
            PackageSource packageSource = new PackageSource(repositoryPath);
            SourceRepository sourceRepository = new SourceRepository(packageSource, Repository.Provider.GetCoreV3());

            // create a resource provider to retrieve package metadata
            List<Lazy<INuGetResourceProvider>> resourceProviders = new List<Lazy<INuGetResourceProvider>>();
            resourceProviders.AddRange(Repository.Provider.GetCoreV3().GetResourceProviders());
            PackageMetadataResourceProvider packageMetadataResourceProvider = new PackageMetadataResourceProvider();
            resourceProviders.Add(new Lazy<INuGetResourceProvider>(() => packageMetadataResourceProvider));

            // create a package metadata resource
            CancellationToken cancellationToken = CancellationToken.None;
            PackageMetadataResource packageMetadataResource = await sourceRepository.GetResourceAsync<PackageMetadataResource>(cancellationToken);

            // get all packages from the local repository
            IEnumerable<IPackageSearchMetadata> allPackages = await packageMetadataResource.GetMetadataAsync("", true, false, resourceProviders, cancellationToken);

            // filter the packages by a specific package ID and version range
            string packageId = "Newtonsoft.Json"; // example package ID
            VersionRange versionRange = VersionRange.Parse("[12.0.1,13.0.0)"); // example version range
            IEnumerable<IPackageSearchMetadata> filteredPackages = allPackages.Where(p => p.Identity.Id.Equals(packageId) && versionRange.Satisfies(p.Identity.Version));

            // display the filtered packages
            Console.WriteLine($"Filtered packages for package ID '{packageId}' and version range '{versionRange}':");
            foreach (var package in filteredPackages)
            {
                Console.WriteLine($"{package.Identity.Id} {package.Identity.Version}");
            }
        }
    }
}