[英]C# reflection: How to load multiple assemblies in different folders
我的代碼使用Assembly.LoadFrom加載主程序集,並使用反射檢查此程序集中的類型和函數。 該程序集引用了不同文件夾中的其他一些程序集。 當我的代碼嘗試檢查那些其他程序集中定義的類型時,將拋出 FileNotFoundException。
我無法使用 app.config 設置來解決這個問題。 這一切都必須以編程方式完成。
我該如何解決這個問題?
我想通了:
private static List<string> m_otherFolderPaths = new List<string> { @"C:\Projects\DllExport\trunk\Example1\HR Interface\bin\Another folder" };
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
// Ignore missing resources
if (args.Name.Contains(".resources"))
return null;
// check for assemblies already loaded
Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == args.Name);
if (assembly != null)
return assembly;
// Try to load by filename - split out the filename of the full assembly name
// and append the base path of the original assembly (ie. look in the same dir)
string filename = args.Name.Split(',')[0] + ".dll".ToLower();
foreach (string folder in m_otherFolderPaths)
{
var assemblyFilePath = Path.Combine(folder, filename);
if (File.Exists(assemblyFilePath))
{
try
{
return Assembly.LoadFrom(assemblyFilePath);
}
catch
{
return null;
}
}
}
return null;
}
static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
PrintAssembly(Assembly.LoadFrom(@"C:\Projects\DllExport\trunk\Example1\HR Interface\bin\au.com.frontedge.DllExport.Example1.DataAccess.dll"));
Console.ReadKey();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.