如何获取当前正在执行的程序集引用的所有程序集的路径? GetReferencedAssmblies()
给了我AssemblyName[]
个。我怎样从那里到达它们的装载位置?
答案 0 :(得分:13)
在加载程序集之前,您无法知道。装配分辨率算法很复杂,您无法可靠地预测它将做什么。调用Assembly.Load(AssemblyName)
覆盖将为您提供对程序集的引用,其Location属性将告诉您所需的内容。
但是,您确实不想在JIT编译器之前预先加载程序集。这是低效的,问题的可能性不是零。例如,您可以在程序准备好响应之前触发AppDomain.AssemblyResolve
事件。避免问这个问题。
答案 1 :(得分:3)
Following Hans Passant's answer, and since the CodeBase
property always contained null
, I came up with this. It might not find all assemblies since they might not all be already loaded. In my situation, I had to find all reference of a previously loaded assembly, so it worked well:
IEnumerable<string> GetAssemblyFiles(Assembly assembly)
{
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
return assembly.GetReferencedAssemblies()
.Select(name => loadedAssemblies.SingleOrDefault(a => a.FullName == name.FullName)?.Location)
.Where(l => l != null);
}
Usage:
var assemblyFiles = GetAssemblyFiles(typeof(MyClass).Assembly);
答案 2 :(得分:0)
CodeBase
属性应提供完整路径名。
答案 3 :(得分:0)
您可以像这样获取程序集的URL位置:
Assembly.GetExecutingAssembly().GetReferencedAssemblies()[0].CodeBase