给定一个解决方案文件的字符串文件路径,例如 C:\Foo.sln,如何以编程方式为该解决方案还原 NuGet 包?我尝试遵循这个指南,但发现它非常不完整。
按照文章建议安装 NuGet.VisualStudio NuGet 包后,我正在努力尝试恢复包。
以下是我目前的代码:
// 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();
}
}