13

I have a C# application, and to organize its files I have some DLL's in a folder called "Data". I want the EXE to check this folder for the DLL's just like how it checks its current directory. If I created a App.Config with this information:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <probing privatePath="Data" />
    </assemblyBinding>
  </runtime>
</configuration>

It works without a problem. I do not want to have an App.Config. Is there a way to set the probing path without using an app.config?

Landin Martens
  • 3,283
  • 12
  • 43
  • 61

2 Answers2

7

You can also handle the AppDomain AssemblyResolve event like so:

AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

and:

private static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    var probingPath = pathToYourDataFolderHere;
    var assyName = new AssemblyName(args.Name);

    var newPath = Path.Combine(probingPath, assyName.Name);
    if (!newPath.EndsWith(".dll"))
    {
        newPath = newPath + ".dll";
    }
    if (File.Exists(newPath))
    {
        var assy = Assembly.LoadFile(newPath);
        return assy;
    }
    return null;
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Darrell
  • 1,905
  • 23
  • 31
  • If you have a dll file in you app folder AND in a subfolder, and want to use the one in the subfolder by preference (because say its a different version), then this is the way to go. The app.config method will always use the dll from the app folder first if there is one, and only look in the paths provided if there isn't one in the local folder. – dylanT Jul 05 '19 at 03:43
5

You can do it for new AppDomains you create, I don't believe there is a way to do it in managed code for current/default AppDomain.

Edit: Creating AppDomain with private path: use AppDomain.CreateDomain and AppDomainSetup.PrivateBinPath

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • +1. No way - that must be set when the AppDomain is created. app.config is evaluated by program start from the runtime. Only alternative is in code, creating a second appdomain. THAT though may be a suable approach. – TomTom Apr 27 '12 at 05:45
  • Updated the answer with links. – Alexei Levenkov Apr 27 '12 at 15:51
  • 1
    That does not work, can you show me where to place it in my code, and maybe a code example? – Landin Martens Apr 28 '12 at 01:46
  • Unclear what you tried in "that". Ask another question starting "When I'm running code in newly created AppDomain my PrivateBinPath is not respected. Here is my code... and this is what I expect to be run in new AppDomain...". – Alexei Levenkov Apr 28 '12 at 01:55