Untitled
unknown
plain_text
3 years ago
2.9 kB
7
Indexable
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.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace NuGetPackageManagerExample
{
class Program
{
static async Task Main(string[] args)
{
string packageId = "Newtonsoft.Json";
string repositoryPath = @"C:\LocalNuGetRepository";
// Create a package source pointing to the local repository
PackageSource localSource = new PackageSource(repositoryPath);
// Create a package source provider with the local source
IPackageSourceProvider packageSourceProvider = new PackageSourceProvider(new Settings());
// Add the local source to the provider
packageSourceProvider.AddPackageSource(localSource);
// Create a package repository provider with the package source provider
PackageRepositoryProvider packageRepositoryProvider = new PackageRepositoryProvider(packageSourceProvider);
// Create a package metadata resource provider with the package repository provider
PackageMetadataResourceProvider metadataResourceProvider = new PackageMetadataResourceProvider();
// Create a source cache context with no cache
SourceCacheContext sourceCacheContext = new SourceCacheContext();
// Create a package metadata resource with the metadata resource provider
PackageMetadataResource metadataResource = await metadataResourceProvider.TryCreatePackageMetadataResourceAsync(localSource, CancellationToken.None, sourceCacheContext);
// Search for the package metadata
IEnumerable<IPackageSearchMetadata> searchMetadata = await metadataResource.GetMetadataAsync(packageId, includePrerelease: false, includeUnlisted: false, Common.NullLogger.Instance, CancellationToken.None);
// Get the latest stable version of the package
NuGetVersion latestVersion = searchMetadata.Max(p => p.Identity.Version);
// Create a package download context with the no cache
PackageDownloadContext downloadContext = new PackageDownloadContext(sourceCacheContext, packageRepositoryProvider);
// Create a package download resource with the download context
PackageDownloadResource downloadResource = await metadataResource.GetResourceAsync<PackageDownloadResource>();
// Download the package to the local repository
await downloadResource.DownloadToStreamAsync(packageId, latestVersion, Console.Out, downloadContext, CancellationToken.None);
Console.WriteLine($"Package {packageId} version {latestVersion} installed to {repositoryPath}");
}
}
}Editor is loading...