After a user does a dotnet add package <SomePackage>
, the DLL will be installed to a path similar to:
C:\Users\USER\.nuget\packages\SomePackage\1.0.2\lib\netstandard2.0\SomePackage.dll
How can I find this path programmatically? I see there's some information in the obj/project.assets.json
that I could parse, and also an interesting DependencyContextJsonReader class under the dotnet github organization.
However, there's no documentation or discussions about this that I can find, and I'm not sure if that's because I'm taking the wrong approach.
Some background:
I'm writing a tool that can scaffold C# projects. It uses a combination of the dotnet
command line tools, and the Roslyn Workspace APIs to interact with the generated project. I'd now like to allow the user to install Nuget packages into this generated solution. I invoke dotnet add package SomePackage
which works fine, and now I'd like to add the DLL to the Roslyn Project
object using the AddReferences
API, which requires the actual DLL.
I found a way to do this using the nuget client libraries.
Essentially, rather than shelling out to the dotnet add package
command, I can use the NuGet client libraries directly from my application to install packages. I then have access to the full path via the PackagePathResolver.GetInstalledPath
method.
Martin Björkström's post, Revisiting the NuGet v3 Libraries, goes into much more detail, and a fully working code sample from Martin is available in this gist.