Asp.net Core Load Assembly

2019-05-26 19:57发布

I am tring to load some .dll files from a folder:

    var fileNames = Directory
        .GetFiles(path, "*.dll", searchOption);
    var assemblyNames = fileNames
        .Select(AssemblyLoadContext.GetAssemblyName);

    List<Assembly> assemblies = new List<Assembly>();
    foreach (AssemblyName assemblyName in assemblyNames)
    {
        assemblies.Add(Assembly.Load(assemblyName));
    }

But somehow the assembly cannot be loaded: FileNotFoundException, Could not load file or assembly [...] The system cannot find the file specified.

How is this possible, because the file is definitely there?

I can provide additional information, if you need more background.

2条回答
▲ chillily
2楼-- · 2019-05-26 20:33

To load a assembly from a file it is easier to use the Assembly.LoadFrom() function. In your application is would look like:

var fileNames = Directory.GetFiles(path, "*.dll", searchOption);

List<Assembly> assemblies = new List<Assembly>(); foreach (string fileName in fileNames) { assemblies.Add(Assembly.LoadFrom(fileName)); }

[Edit]

If you are attempting to load the assemblies for later use in the application (e.g. you have reference to the assembly in Visual Studio), it is recommend that you implement the AppDomain.AssemblyResolve event. The AppDomain.AssemblyResolve event will fire when an assembly cannot be found and needs to be loaded. At that time you can provide the AppDomain an assembly in a different file location.

查看更多
疯言疯语
3楼-- · 2019-05-26 20:52

With these using statements:

using System.Reflection;
using System.Runtime.Loader;

Try this:

var myAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(pathTodll);
查看更多
登录 后发表回答