如何在.NET中添加文件夹集搜索路径在运行时?文件夹、路径、如何在、NET

2023-09-02 10:15:54 作者:Obsession(痴狂/迷恋/偏执)

我的DLL是由第三方应用程序,这是我们不能自定义加载。我的组件必须位于其自己的文件夹。我不能把它们放进GAC(我的应用程序要求使用XCOPY部署)。 当根DLL尝试从另一个DLL(在相同的文件夹中)加载资源或类型,装载失败(FileNotFound)。 是否有可能加入其中,我的DLL(从根DLL)位于装配搜索路径编程方式的文件夹?我不能更改应用程序的配置文件。

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 application has a requirement to be deployed using XCOPY). When the root DLL tries to load resource or type from another DLL (in the same folder), the loading fails (FileNotFound). Is it possible to add the folder where my DLLs are located to the assembly search path programmatically (from the root DLL)? I am not allowed to change the configuration files of the application.

推荐答案

听起来像是你可以使用AppDomain.AssemblyResolve事件和手动从DLL目录加载的依赖关系。

Sounds like you could use the AppDomain.AssemblyResolve event and manually load the dependencies from your DLL directory.

编辑(从评论):

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromSameFolder);

static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args)
{
    string folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    string assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll");
    if (File.Exists(assemblyPath) == false) return null;
    Assembly assembly = Assembly.LoadFrom(assemblyPath);
    return assembly;
}