简体   繁体   中英

C# reflection: How to load multiple assemblies in different folders

My code uses Assembly.LoadFrom to load the main assembly, and uses reflection to inspect the types and functions in this assembly. This assembly references some other assemblies which are in different folders. When my code tries to inspect the types defined in those other assemblies, FileNotFoundException is thrown.

I can't use app.config setting to solve this problem. It all has to be done programmatically.

How do I solve this problem?

I figured out:

    private static List<string> m_otherFolderPaths = new List<string> { @"C:\Projects\DllExport\trunk\Example1\HR Interface\bin\Another folder" };

    private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        // Ignore missing resources
        if (args.Name.Contains(".resources"))
            return null;

        // check for assemblies already loaded
        Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == args.Name);
        if (assembly != null)
            return assembly;

        // Try to load by filename - split out the filename of the full assembly name
        // and append the base path of the original assembly (ie. look in the same dir)
        string filename = args.Name.Split(',')[0] + ".dll".ToLower();

        foreach (string folder in m_otherFolderPaths)
        {
            var assemblyFilePath = Path.Combine(folder, filename);

            if (File.Exists(assemblyFilePath))
            {
                try
                {
                    return Assembly.LoadFrom(assemblyFilePath);
                }
                catch
                {
                    return null;
                }
            }
        }

        return null;
    }

    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        PrintAssembly(Assembly.LoadFrom(@"C:\Projects\DllExport\trunk\Example1\HR Interface\bin\au.com.frontedge.DllExport.Example1.DataAccess.dll"));
        Console.ReadKey();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM