更改.NET应用程序的程序集解析位置

qgelzfjb  于 2023-01-10  发布在  .NET
关注(0)|答案(3)|浏览(146)

我正在尝试修改2.exs以从1个位置加载DevExpress dll。
"产品"文件夹中的. exe使用的是与启动程序相同的. dll。我想避免将相同的. dll放入产品目录,而是从1目录(启动程序目录)读取. exe。
我怎样才能做到这一点?

kzipqqlq

kzipqqlq1#

您可以处理AppDomain.AssemblyResolve事件,并使用Assembly.LoadFile自行从目录加载程序集,该文件提供了程序集尝试解析的程序集的完整路径。
示例:

.
.
.
// elsewhere at app startup time attach the handler to the AppDomain.AssemblyResolve event
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
.
.
.

private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    AssemblyName assemblyName = new AssemblyName(args.Name);

    // this.ReadOnlyPaths is a List<string> of paths to search.
    foreach (string path in this.ReadOnlyPaths)
    {
        // If specified assembly is located in the path, use it.
        DirectoryInfo directoryInfo = new DirectoryInfo(path);

        foreach (FileInfo fileInfo in directoryInfo.GetFiles())
        {
             string fileNameWithoutExt = fileInfo.Name.Replace(fileInfo.Extension, "");                    

             if (assemblyName.Name.ToUpperInvariant() == fileNameWithoutExt.ToUpperInvariant())
             {
                  return Assembly.Load(AssemblyName.GetAssemblyName(fileInfo.FullName));
             }
        }
    }
    return null;
}
nimxete2

nimxete22#

您可以在app.config中的assemblyBinding〉probing::privatePath标记中设置文件夹路径,以便公共语言运行库在加载程序集时进行搜索。
Reference MSDN

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <probing privatePath="libs" />
  </assemblyBinding>
</runtime>
</configuration>
9rbhqvlz

9rbhqvlz3#

您可以创建类:

using System;
using System.Reflection;

namespace myNamespace
{
    public sealed class EntryPoint
    {
        [STAThread]
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
            var app = new App();
            app.InitializeComponent();
            app.Run();
        }
        private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
        {
            // do whatever necessary...
        }
    }
}

由于WPF已经有了一个内置的Main()方法,你会得到一个编译器错误。所以转到项目属性〉应用程序〉“启动对象”并将其设置为myNamespace.EntryPoint。在你自己的Main()方法中,你可以完全控制一切,所以你可以在示例化App之前设置AssemblyResolve处理程序。

相关问题