给定解决方案文件的字符串文件路径,例如C:\Foo.sln,您如何以编程方式恢复该解决方案的 NuGet 包?我试着关注 this guide ,但发现它严重不完整。
按照文章的建议安装 NuGet 包 NuGet.VisualStudio 后,我在尝试恢复包时陷入困境。
这是我目前的代码:
// requires reference to System.ComponentModel.Composition
[Import(typeof(IVsPackageRestorer))]
private static IVsPackageRestorer packageInstaller;
然后尝试使用它(似乎需要 EnvDTE 引用)(以及如何使用这种神奇的“GetService”方法 - 它从何而来?):
private static void RestorePackages(string solutionPath)
{
// Using the IComponentModel service
// https://learn.microsoft.com/en-us/nuget/visual-studio-extensibility/nuget-api-in-visual-studio#ivspackagerestorer-interface
// How do I get the project? Can I do this at the solution level or do I have to get all projects under the solution?
EnvDTE.Project project = null;
packageInstaller.RestorePackages(project);
////What is this code??? What is GetService???
////var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
////IVsPackageRestorer packageRestorer = componentModel.GetService<IVsPackageRestorer>();
////packageRestorer.RestorePackages(project);
}
编辑/解决方案:根据 Matt Ward 的建议,“提取”到 nuget.exe 的代码在我的案例中类似于以下方法,用于根据解决方案的完整路径恢复包。
private static void RestorePackages(string solutionPath)
{
using (Process process = new Process())
{
process.StartInfo = new ProcessStartInfo
{
FileName = "nuget.exe",
Arguments = $"restore {solutionPath}",
UseShellExecute = false,
CreateNoWindow = true
};
process.Start();
process.WaitForExit();
}
}
最佳答案
不确定您的代码从哪里运行。直接退出 NuGet.exe 并恢复解决方案而不是尝试使用 Visual Studio API 可能更简单。例如,仅当您作为扩展从 Visual Studio 中运行或在程序包管理器控制台窗口中运行时,您链接到的 API 才可用。
如果您编写的代码不在 Visual Studio 中运行,假设它是一个控制台应用程序,那么运行 nuget.exe 会更容易。否则,您可以查看可供使用的各种 NuGet 包,并提供一个 API 来执行各种 NuGet 操作。然而,运行 nuget.exe 恢复要简单得多。
关于C# 以编程方式恢复 NuGet 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47582257/