C# Set probing privatePath without app.config?

房东的猫 提交于 2019-11-29 17:40:00

问题


I have a C# application, and to organize its files I have some DLL's in a folder called "Data". I want the EXE to check this folder for the DLL's just like how it checks its current directory. If I created a App.Config with this information:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <probing privatePath="Data" />
    </assemblyBinding>
  </runtime>
</configuration>

It works without a problem. I do not want to have an App.Config. Is there a way to set the probing path without using an app.config?


回答1:


You can do it for new AppDomains you create, I don't believe there is a way to do it in managed code for current/default AppDomain.

Edit: Creating AppDomain with private path: use AppDomain.CreateDomain and AppDomainSetup.PrivateBinPath




回答2:


You can also handle the AppDomain AssemblyResolve event like so:

AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

and:

 private static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        var probingPath = pathToYourDataFolderHere;
        var assyName = new AssemblyName(args.Name);

        var newPath = Path.Combine(probingPath, assyName.Name);
        if (!newPath.EndsWith(".dll"))
        {
            newPath = newPath + ".dll";
        }
        if (File.Exists(newPath))
        {
            var assy = Assembly.LoadFile(newPath);
            return assy;
        }
        return null;
    }


来源:https://stackoverflow.com/questions/10345240/c-sharp-set-probing-privatepath-without-app-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!