【发布时间】:2017-01-23 10:08:57
【问题描述】:
我想以编程方式将 NuGet 包安装到项目中,并更新 .csproj 文件和 packages.config 文件。
我使用的是官方的Nuget.core 框架,源代码在这里:https://github.com/NuGet/NuGet2
我没有使用 NuGet 包:https://www.nuget.org/packages/NuGet.Core/ 但是在GitHub上找到的源代码可以做一些调试。
注意:我使用的是
2.11版本,而不是2.13
我可以在所需目录下载包并更新packages.config 文件:
// ---- Download and install a package at a desired path ----
string packageID = "Newtonsoft.json";
var sourceUri = new Uri("https://packages.nuget.org/api/v2");
// Return an IPackage
var package = GetNugetPackage(packageID, sourceUri);
IPackageRepository sourceRepository = PackageRepositoryFactory.Default.CreateRepository(sourceUri.ToString());
string packagesPath = "../../TestFiles/packages";
PackageManager packageManager = new PackageManager(sourceRepository, packagesPath);
packageManager.InstallPackage(packageID, SemanticVersion.Parse(package.Version.ToFullString()));
// ---- Update the ‘packages.config’ file ----
var packageReferenceFile = new PackageReferenceFile("../../TestFiles/packages.config");
// Get the target framework of the current project to add --> targetframework="net452" attribute in the package.config file
var currentTargetFw = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(TargetFrameworkAttribute), false);
var targetFrameworkAttribute = ((TargetFrameworkAttribute[])currentTargetFw).FirstOrDefault();
// Update the packages.config file
packageReferenceFile.AddEntry(package.GetFullName(), SemanticVersion.Parse(package.Version.ToFullString()), false, new FrameworkName(targetFrameworkAttribute.FrameworkName));
现在我需要更新.csproj,这是棘手的部分...
到目前为止,这是我尝试过的:
string csprojFilePath = "../../TestFiles/test.csproj";
var project = new MSBuildProjectSystem(csprojFilePath);
string pathToAnExistingNugetPackageDll = "../../TestFiles/packages/Newtonsoft.json/lib/net45/Newtonsoft.json.dll"
project.AddReference(pathToAnExistingNugetPackageDll, Stream.Null);
project.Save();
这段代码更新了.csproj 文件,它添加了一个新的reference 节点,如下所示:
<Reference Include="Newtonsoft.json">
<HintPath>..\packages\Newtonsoft.json\lib\net45\Newtonsoft.json.dll</HintPath>
</Reference>
但我需要一个 完整 reference 节点,如下所示:
<Reference Include="Newtonsoft.json, Version=9.0.8, Culture=neutral, PublicKeyToken=b03f4f7d11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.json\lib\net45\Newtonsoft.json.dll</HintPath>
<Private>True</Private>
</Reference>
我该怎么做?
【问题讨论】:
-
您需要使用自己的代码自己生成参考。这种特定的引用样式是由 Visual Studio 生成的,而不是由 NuGet 生成的。 NuGet 使用不使用完整程序集名称的 Include 属性生成引用。
-
我在核心程序集中找到了一个似乎可以解决问题的类:'RemoteAssembly' 它似乎加载了我需要的属性......我会试一试