Reputation: 1305
On my local file System I have the nuget package foo.nupkg
. It contains the assembly foo.dll
.
If I manually extract the foo.nupkg
I can programmatically load the foo.dll
assembly as follows:
AssemblyLoadContext.Default.LoadFromAssemblyPath("c:/path/foo.dll");
How can I load the assembly from foo.nupkg
directly?
What I already tried:
.nupkg
file to a temporary directory but I wonder if this is really required.NuGet.Core
. I provides a PackageManager#InstallPackage
that accepts an IPackage
. But it seems that IPackage
instances can only be revtrieved from repositories (which I don't have).Upvotes: 1
Views: 607
Reputation: 26792
A nuget package is just a zip file, so you could simply use System.IO.Compression.ZipArchive to read it.
You can also load an assembly from a byte array, so something like this should work (assuming newtonsoft.json package is in the working directory):
using var archive = ZipFile.OpenRead("newtonsoft.json.12.0.3.nupkg");
var entry = archive.GetEntry("lib/netstandard2.0/Newtonsoft.Json.dll");
using var target = new MemoryStream();
using var source = entry.Open();
source.CopyTo(target);
var assembly = Assembly.Load(target.ToArray());
var type = assembly.GetType("Newtonsoft.Json.JsonConvert");
Console.WriteLine(type.FullName);
Upvotes: 4