Marteng
Marteng

Reputation: 1305

Programmatically Load Assembly From Local Nuget Package File

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:

Upvotes: 1

Views: 607

Answers (1)

jeroenh
jeroenh

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

Related Questions