C#设置探测privatePath而不用app.config?

Lan*_*ens 12 c# app-config private path probing

我有一个C#应用程序,为了组织它的文件,我在一个名为"Data"的文件夹中有一些DLL.我希望EXE检查此文件夹中的DLL,就像它检查当前目录一样.如果我使用以下信息创建了App.Config:

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

它没有问题.我不想要App.Config.有没有办法在不使用app.config的情况下设置探测路径?

Ale*_*kov 5

您可以为您创建的新 AppDomain 执行此操作,我认为没有办法在当前/默认 AppDomain 的托管代码中执行此操作。

编辑:使用私有路径创建 AppDomain:使用AppDomain.CreateDomainAppDomainSetup .PrivateBinPath


Dar*_*ell 5

您还可以AssemblyResolve像这样处理AppDomain 事件:

AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
Run Code Online (Sandbox Code Playgroud)

和:

 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;
    }
Run Code Online (Sandbox Code Playgroud)