【问题标题】:C# Set probing privatePath without app.config?C#在没有app.config的情况下设置探测privatePath?
【发布时间】:2012-05-07 21:12:12
【问题描述】:

我有一个 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>

它可以正常工作。我不想拥有 App.Config。有没有办法在不使用 app.config 的情况下设置探测路径?

【问题讨论】:

    标签: c# path app-config private probing


    【解决方案1】:

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

    AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
    

    和:

    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;
    }
    

    【讨论】:

    • 如果您的应用程序文件夹和子文件夹中有一个 dll 文件,并且希望优先使用子文件夹中的那个(因为说它是不同的版本),那么这就是要走的路. app.config 方法总是会首先使用 app 文件夹中的 dll,如果有的话,如果本地文件夹中没有,则只查找提供的路径。
    【解决方案2】:

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

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

    【讨论】:

    • +1。没办法 - 必须在创建 AppDomain 时设置。 app.config 由程序从运行时开始评估。唯一的选择是在代码中,创建第二个 appdomain。不过,这可能是一种可行的方法。
    • 用链接更新了答案。
    • 这不起作用,你能告诉我在我的代码中放置它的位置吗,也许是一个代码示例?
    • 不清楚你在“那个”中尝试了什么。问另一个问题,开始“当我在新创建的 AppDomain 中运行代码时,我的 PrivateBinPath 不受尊重。这是我的代码......这就是我希望在新的 AppDomain 中运行的......”。
    猜你喜欢
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    相关资源
    最近更新 更多