gpt4 book ai didi

c# - 如何使用 NuGet v3 API 下载和解压缩包

转载 作者:太空狗 更新时间:2023-10-29 22:57:20 25 4
gpt4 key购买 nike

我一直在使用我在 http://blog.nuget.org/20130520/Play-with-packages.html 上找到的 NuGet.Core 包中的以下代码

//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 以编程方式下载和解压缩包?

最佳答案

简介

我在一些项目中使用了 nuget v2。最近测试了nuget v3,因为有很多包报错提示使用nuget v3。所以我尝试在示例项目中测试 nuget v3。我不是专家,但下载有效。

项目类型

我发现了 3 种类型的 NuGet 项目。

  • PackagesConfigNuGetProject
  • 文件夹NuGet项目
  • MSBuildNuGet项目

PackagesConfigNuGetProject:

Represents a NuGet project as represented by packages.config.

Note : It will download your package in the packages.config (in fact, it will add an entry for your package in the packages.config). Your NuGet package won't be in your disk, only in the packages.config. So if you want to get or use the dll, you need to use the FolderNuGetProject #

文件夹NuGet项目:

This class represents a NuGetProject based on a folder such as packages folder on a VisualStudio solution.

Use this class if you want your packages installed on your disk. #

MSBuildNuGetProject:

This class represents a NuGetProject based on a .NET project. This also contains an instance of a 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 包时要小心。它会卡住用户界面。您应该使用 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;
}
}

希望对您有所帮助!

关于c# - 如何使用 NuGet v3 API 下载和解压缩包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39569318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com