How to add folder to assembly search path at runtime in .NET?

前端 未结 8 2178
慢半拍i
慢半拍i 2020-11-22 07:08

My DLLs are loaded by a third-party application, which we can not customize. My assemblies have to be located in their own folder. I can not put them into GAC (my applicatio

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 07:53

    The best explanation from MS itself:

    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
    
    private Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
    {
        //This handler is called only when the common language runtime tries to bind to the assembly and fails.
    
        //Retrieve the list of referenced assemblies in an array of AssemblyName.
        Assembly MyAssembly, objExecutingAssembly;
        string strTempAssmbPath = "";
    
        objExecutingAssembly = Assembly.GetExecutingAssembly();
        AssemblyName[] arrReferencedAssmbNames = objExecutingAssembly.GetReferencedAssemblies();
    
        //Loop through the array of referenced assembly names.
        foreach(AssemblyName strAssmbName in arrReferencedAssmbNames)
        {
            //Check for the assembly names that have raised the "AssemblyResolve" event.
            if(strAssmbName.FullName.Substring(0, strAssmbName.FullName.IndexOf(",")) == args.Name.Substring(0, args.Name.IndexOf(",")))
            {
                //Build the path of the assembly from where it has to be loaded.                
                strTempAssmbPath = "C:\\Myassemblies\\" + args.Name.Substring(0,args.Name.IndexOf(","))+".dll";
                break;
            }
    
        }
    
        //Load the assembly from the specified path.                    
        MyAssembly = Assembly.LoadFrom(strTempAssmbPath);                   
    
        //Return the loaded assembly.
        return MyAssembly;          
    }
    

提交回复
热议问题