C# 引用子文件夹中的 dll

C# Referencing dll in subfolder

我不知道我做错了什么。

我的项目是这样的:

MainProject

SubProject (referencing my desires DLL)

我有我的 app.config(MainProject):

<configuration>
  <configSections>
    <section name="DirectoryServerConfiguration" type="System.Configuration.NameValueSectionHandler"/>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
    <section name="GeneralConfiguration" type="System.Configuration.NameValueSectionHandler"/>
    <section name="ServerConnectionConfiguration" type="System.Configuration.NameValueSectionHandler"/>
    <section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings,Microsoft.Practices.EnterpriseLibrary.Caching"/>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
  </startup>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <probing privatePath="ReferencesDLL" />
    </assemblyBinding>
  </runtime>

  <GeneralConfiguration configSource="ConfigFiles\GeneralConfiguration.config"/>
  <cachingConfiguration configSource="ConfigFiles\cachingConfiguration.config"/>
  <DirectoryServerConfiguration configSource="ConfigFiles\YPAdress.config"/>
  <log4net configSource="ConfigFiles\log4net.config"/>
</configuration>

我的编译库是这样的:

如您所见,我定义了 privatePath,但是当 运行 应用程序时,它找不到 SubProject 所需的 dll。 (.config 文件没问题) 我不知道我做错了什么:( .

您可以使用 AppDomain.AssemblyResolve 事件处理程序在已知位置手动查找程序集:

static void Run()
{
    AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

    // Do work...

    AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
}

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    var dllName = new AssemblyName(args.Name).Name + ".dll";
    var assemblyPath = Assembly.GetExecutingAssembly().Location;

    var referenceDirectory = new DirectoryInfo(Path.Combine(Path.GetDirectoryName(assemblyPath), "ReferencesDLL"));
    if (!referenceDirectory.Exists)
        return null; // Can't find the reference directory

    var assemblyFile = referenceDirectory.EnumerateFiles(dllName, SearchOption.TopDirectoryOnly).FirstOrDefault();
    if (assemblyFile == null)
        return null; // Can't find a matching dll

    return Assembly.LoadFrom(assemblyFile.FullName);
}