magbo system

In my company we wanted to bring together external dlls into one folder named “Libs” next to the executable. Indeed, when you have many dlls (and not all written in C#), it’s more readable to put them all in one folder that contains the dependencies of the project.

1. Add required files then set parameters

The first step is to create a “Libs” folder in your project then add all required files.
Select your all dlls then set the option “Copy to Ouput Directory” to “true“.

Note: If you put some C# dlls in the “Libs” folder” while they are also in the References” section, be sure that you set the “Copy Local” option to “false” in order to have only  once the same file in your output.

2. Specify where your program must load the assembly

In my case we are in a WPF application but you can do this in your entry point whatever your type of project.

In the constructor, we have to subscribe to the AssemblyResolve event that is called for each dll. When a dll should be loaded, our handler will override de default behavior only if the current dll is in the Libs folder.

/// 
/// Initialize the Application
/// 
public App()
{
    var domain = AppDomain.CurrentDomain;
    domain.AssemblyResolve += LoadAssembly;
}
/// 
/// Include externals dlls
/// 
private Assembly LoadAssembly(object sender, ResolveEventArgs args)
{
    Assembly result = null;
    if (args != null && !string.IsNullOrEmpty(args.Name))
    {
        //Get current exe fullpath
        FileInfo info = new FileInfo(Assembly.GetExecutingAssembly().Location);
 
        //Get folder of the executing .exe
        var folderPath = Path.Combine(info.Directory.FullName, "Libs");
 
        //Build potential fullpath to the loading assembly
        var assemblyName = args.Name.Split(new string[] { "," }, StringSplitOptions.None)[0];
        var assemblyExtension = "dll";
        var assemblyPath = Path.Combine(folderPath, string.Format("{0}.{1}", assemblyName, assemblyExtension));
 
        //Check if the assembly exists in our "Libs" directory
        if (File.Exists(assemblyPath))
        {
            //Load the required assembly using our custom path
            result = Assembly.LoadFrom(assemblyPath);
        }
        else
        { 
            //Keep default loading
            return args.RequestingAssembly;
        }
    }
 
    return result;
}
Last modified: 15 February 2016

Author

Comments

Very useful…I just wanted it.
thanks a lot

Write a Reply or Comment

Your email address will not be published.