C# Set probing privatePath without app.config?

Landin Martens picture Landin Martens · Apr 27, 2012 · Viewed 14.3k times · Source

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?

Answer

Darrell picture Darrell · Apr 9, 2017

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