从非根目录加载程序集

时间:2019-04-07 08:45:52

标签: c# directory .net-assembly

我正在尝试从根目录之外的其他文件夹中将程序集加载到我的项目中,并为此设置一个新域。我的目标是在运行时加载和卸载。当ddl文件位于应用程序的根目录中时,所有工作正常,但是一旦将其放入文件夹插件中,就找不到错误文件。我知道有很多这样的话题,但是没有一个能满足我的所有需求,而且除了恐惧之外,它们都不起作用。一旦我加载到当前域,它就可以工作。

示例代码:

  dllFileNames = Directory.GetFiles(path, "*.dll");

                ICollection<Assembly> assemblies = new List<Assembly>(dllFileNames.Length);

                AppDomain currentDomain = AppDomain.CurrentDomain;
                Evidence asEvidence = currentDomain.Evidence;
                AppDomainSetup aps = new AppDomainSetup
                {
                    ApplicationBase = @"[root of application]",
                    PrivateBinPath = @"[Plugin folder]"
                };

                AppDomain myDomain = AppDomain.CreateDomain("Plugins",asEvidence,aps);
                SimpleAssemblyLoader assemblyLoader = (SimpleAssemblyLoader)myDomain.CreateInstanceAndUnwrap(typeof(SimpleAssemblyLoader).Assembly.FullName, typeof(SimpleAssemblyLoader).FullName);

                foreach (string dllFile in dllFileNames)
                {

                         assemblyLoader.LoadFrom(dllFile);

                }

              var assemblyList =  myDomain.GetAssemblies(); // in here getting error :( file not found for no reason.
  

System.IO.FileNotFoundException:'无法加载文件或程序集'Name,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'或其依赖项之一。系统找不到指定的文件。'

public class SimpleAssemblyLoader : MarshalByRefObject
{
    public void Load(string path)
    {
        ValidatePath(path);

        Assembly.Load(path);
    }

    public void LoadFrom(string path)
    {
        ValidatePath(path);

        Assembly.LoadFrom(path);
    }

    private void ValidatePath(string path)
    {
        if (path == null)
        {
            throw new ArgumentNullException("path");
        }

        if (!System.IO.File.Exists(path))
        {
            throw new ArgumentException(string.Format("path \"{0}\" does not exist", path));
        }
    }
}

1 个答案:

答案 0 :(得分:1)

AppDomain.BaseDirectory设置到您的插件文件夹。

或注册AppDomain.AssemblyResolve事件以解决缺少的程序集。

对于.Net Core编程,请看一下AssemblyLoadContext