我一直在使用NuGet.Core包中的以下代码,我在http://blog.nuget.org/20130520/Play-with-packages.html上找到了
//ID of the package to be looked up
string packageID = "EntityFramework";
//Connect to the official package repository
IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");
//Initialize the package manager string path = <PATH_TO_WHERE_THE_PACKAGES_SHOULD_BE_INSTALLED>
PackageManager packageManager = new PackageManager(repo, path);
//Download and unzip the package
packageManager.InstallPackage(packageID, SemanticVersion.Parse("5.0.0"));
这非常有效,但我不得不将框架更新为.NET Core,NuGet.Core包不支持。 我认为NuGet.Protocol.Core.v3包应该有我需要的东西,但是我找不到办法。我在http://daveaglick.com/posts/exploring-the-nuget-v3-libraries-part-1
上找到了大量有关NuGet v3 API的信息所以我的问题是:如何使用NuGet v3以编程方式下载和解压缩包?
答案 0 :(得分:6)
我在某些项目中使用nuget v2。最近,我测试了nuget v3,因为有很多软件包会抛出错误,表明使用了nuget v3。所以我试着在一个示例项目中测试nuget v3。我不是专家,但下载有效。
我找到了3种类型的NuGet项目。
PackagesConfigNuGetProject:
表示由packages.config表示的NuGet项目。
注意:它将在packages.config中下载您的软件包(实际上,它将在packages.config中为您的软件包添加一个条目)。您的NuGet包不会出现在您的磁盘中,只能在packages.config中。因此,如果您想获取或使用dll,则需要使用FolderNuGetProject #
FolderNuGetProject:
此类表示基于VisualStudio解决方案上的packages文件夹等文件夹的NuGetProject。
如果要在磁盘上安装软件包,请使用此类。 #
MSBuildNuGetProject:
此类表示基于.NET项目的NuGetProject。这还包含FolderNuGetProject的实例
我不知道您要使用的项目类型。在本例中,我选择了FolderNuGetProject。
1-初始化源存储库
List<Lazy<INuGetResourceProvider>> providers = new List<Lazy<INuGetResourceProvider>>();
providers.AddRange(Repository.Provider.GetCoreV3());
PackageSource packageSource = new PackageSource("https://api.nuget.org/v3/index.json");
SourceRepository sourceRepository = new SourceRepository(packageSource, providers);
Logger logger = new Logger();
2-初始化Nuget包管理器
var rootPath = @"yourPathToNugetFolder";
var settings = Settings.LoadDefaultSettings(rootPath, null, new MachineWideSettings());
var packageSourceProvider = new PackageSourceProvider(settings);
var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, providers);
var project = new FolderNuGetProject(rootPath);
var packageManager = new NuGetPackageManager(sourceRepositoryProvider, settings, rootPath)
{
PackagesFolderNuGetProject = project
};
3-搜索包(在本例中我选择了:Newtonsoft.Json)
var searchResource = await sourceRepository.GetResourceAsync<PackageSearchResource>();
var supportedFramework = new[] { ".NETFramework,Version=v4.6" };
var searchFilter = new SearchFilter(true)
{
SupportedFrameworks = supportedFramework,
IncludeDelisted = false
};
var jsonNugetPackages = await searchResource
.SearchAsync("Newtonsoft.Json", searchFilter, 0, 10, logger, CancellationToken.None);
4-安装包(Newtonsoft.Json)
在项目中安装nuget包时要小心。它将冻结UI。您应该使用BackgroundWorker或类似的东西来执行此过程。
var allowPrereleaseVersions = true;
var allowUnlisted = false;
INuGetProjectContext projectContext = new ProjectContext();
ResolutionContext resolutionContext = new ResolutionContext(
DependencyBehavior.Lowest,
allowPrereleaseVersions,
allowUnlisted,
VersionConstraints.None);
var jsonPackage = jsonNugetPackages.First();
var identity = new PackageIdentity(jsonPackage.Identity.Id, jsonPackage.Identity.Version);
await packageManager.InstallPackageAsync(
project,
identity,
resolutionContext,
projectContext,
sourceRepository,
new List<SourceRepository>(),
CancellationToken.None);
5-实用工具类
public class MachineWideSettings : IMachineWideSettings
{
private readonly Lazy<IEnumerable<Settings>> _settings;
public MachineWideSettings()
{
var baseDirectory = NuGetEnvironment.GetFolderPath(NuGetFolderPath.MachineWideConfigDirectory);
_settings = new Lazy<IEnumerable<Settings>>(
() => global::NuGet.Configuration.Settings.LoadMachineWideSettings(baseDirectory));
}
public IEnumerable<Settings> Settings => _settings.Value;
}
public class Logger : ILogger
{
private List<string> logs = new List<string>();
public void LogDebug(string data)
{
logs.Add(data);
}
public void LogVerbose(string data)
{
logs.Add(data);
}
public void LogInformation(string data)
{
logs.Add(data);
}
public void LogMinimal(string data)
{
logs.Add(data);
}
public void LogWarning(string data)
{
logs.Add(data);
}
public void LogError(string data)
{
logs.Add(data);
}
public void LogInformationSummary(string data)
{
logs.Add(data);
}
public void LogErrorSummary(string data)
{
logs.Add(data);
}
}
public class ProjectContext : INuGetProjectContext
{
private List<string> logs = new List<string>();
public List<string> GetLogs()
{
return logs;
}
public void Log(MessageLevel level, string message, params object[] args)
{
var formattedMessage = String.Format(message, args);
logs.Add(formattedMessage);
// Do your logging here...
}
public FileConflictAction ResolveFileConflict(string message)
{
logs.Add(message);
return FileConflictAction.Ignore;
}
public PackageExtractionContext PackageExtractionContext
{
get;
set;
}
public NuGet.ProjectManagement.ExecutionContext ExecutionContext
{
get;
}
public XDocument OriginalPackagesConfig
{
get; set;
}
public ISourceControlManagerProvider SourceControlManagerProvider
{
get;
set;
}
public void ReportError(string message)
{
logs.Add(message);
}
public NuGetActionType ActionType
{
get; set;
}
public TelemetryServiceHelper TelemetryService
{
get; set;
}
}
希望这会对你有帮助!