简体   繁体   中英

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:

  • Of course I can programmatically extract the .nupkg file to a temporary directory but I wonder if this is really required.
  • I tried using package 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).

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM