Search code examples
c#visual-studiodlldll-reference

C# Referencing dll in subfolder


i can't figure out what i do wrong.

My project is like that :

MainProject

SubProject (referencing my desires DLL)

I have my app.config (of 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>

And my compile repository is like that :

  • Debug
    • ConfigFiles\ (All the .config files defined in the app.config)
    • ReferencesDLL\ (All the Dll needed by SubProject)
    • (All the others compiled files : .exe, .dll, etc..)

As you can see, i have my privatePath define, but when running the app, it can't find the needed dll for SubProject. (no problem for the .config files) I don't know what i did wrong :( .


Solution

  • You could manually look for the assembly at the known location using an AppDomain.AssemblyResolve event handler:

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