C#编程:以编程方式还原NuGet软件包

3
给定一个解决方案文件的字符串文件路径,例如 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();
    }
}

有时候为了避免弹出许可证窗口等情况,需要在参数中添加“-Verbosity quiet”。参数 = $“restore {solutionPath} -Verbosity quiet”。 - Chirag
1个回答

2

不确定您的代码是从哪里运行的。可能更简单的方法是直接调用NuGet.exe并还原解决方案,而不是尝试使用Visual Studio API。您链接到的API仅在作为扩展或包管理器控制台窗口中运行时才可用,例如在Visual Studio中运行。

如果您编写的代码不在Visual Studio中运行,比如一个控制台应用程序,那么运行nuget.exe会更容易。否则,您可以查看可用于执行各种NuGet操作并提供API的各种NuGet软件包。但是,运行nuget.exe restore要简单得多。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接