动态加载及调用程序集


static DbCmd()
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

        }
        static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
        {
            string strFielName = args.Name.Split(',')[0];
            if (strFielName.ToLower().EndsWith(".resources"))  //不处理资源文件
                return null;
            ExtMethod.WriteLog("DbCmd 程序集获取失败,准备动态加载:" + args.Name);
            string parentRoot = AppDomain.CurrentDomain.BaseDirectory;
            string dllName = GetDllOrExeName(parentRoot, strFielName);
            if (dllName == "")
            {
                parentRoot = System.IO.Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\'));
                dllName = GetDllOrExeName(parentRoot, strFielName);
            }
            if (dllName != null)
            {
                ExtMethod.WriteLog("DbCmd 程序集开始加载文件:" + dllName);
                return Assembly.LoadFile(dllName);
            }
            else
            {
                ExtMethod.WriteLog("DbCmd 程序集获取失败:找不到文件" + strFielName);
            }
            return null;
        }
        /// <summary>
        /// 获取指定名称的dll路径
        /// </summary>
        /// <param name="_DirectoryName">目录路径</param>
        /// <param name="_assemablName">程序集名称</param>
        /// <returns>返回路径名称</returns>
        static string GetDllOrExeName(string _DirectoryName, string _assemablName)
        {
            string filter = _assemablName + ".???";
            var subFiles = System.IO.Directory.GetFiles(_DirectoryName, filter, System.IO.SearchOption.AllDirectories);
            string dllName = "";
            foreach (var item in subFiles) //搜索下级目录
            {
                if (item.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
                {
                    dllName = item;
                    break;
                }
                if (item.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
                {
                    dllName = item;
                    break;
                }
            }
            return dllName;
        }
posted @ 2021-01-15 13:06  梦想(胡大利)  阅读(135)  评论(0编辑  收藏