Kee*_*ker 8 c# reflection assemblies activator c#-2.0
我正在使用Activator基于程序集的短名称来实例化一个新类(例如'CustomModule').它抛出一个FileNotFoundException,因为装配不在那里.有没有办法检查是否存在某个程序集名称?
我正在使用以下代码:
System.Runtime.Remoting.ObjectHandle obj =
System.Activator.CreateInstance(assemblyName, className);
Run Code Online (Sandbox Code Playgroud)
主要目标是测试组件的存在而不是等待异常发生.
如果你会发现我对你的问题的评论也很明显,我不能正确地知道究竟如何你想要或需要去了解这一点,但直到我们有更详尽的描述,我只能你这个报价,希望它适合您的情况(关键是'搜索'程序集):
var className = "System.Boolean";
var assemblyName = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var assembly = (from a in assemblies
where a.FullName == assemblyName
select a).SingleOrDefault();
if (assembly != null)
{
System.Runtime.Remoting.ObjectHandle obj =
System.Activator.CreateInstance(assemblyName, className);
}
Run Code Online (Sandbox Code Playgroud)
.NET 2.0兼容代码
Assembly assembly = null;
var className = "System.Boolean";
var assemblyName = "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
{
if (a.FullName == assemblyName)
{
assembly = a;
break;
}
}
if (assembly != null)
{
System.Runtime.Remoting.ObjectHandle obj =
System.Activator.CreateInstance(assemblyName, className);
}
Run Code Online (Sandbox Code Playgroud)
如果你想在尝试加载它之前确定文件是否存在(一个好的做法)那么,如果你有它的名字并知道所需的位置,只需在解决程序集时找到该文件:
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
var className = "StackOverflowLib.Class1";
var assemblyName = "StackOverflowLib.dll";
var currentAssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var obj = Activator.CreateInstance(Path.Combine(currentAssemblyPath, assemblyName), className);
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var currentAssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (File.Exists(Path.Combine(currentAssemblyPath, args.Name)))
{
return Assembly.LoadFile(Path.Combine(currentAssemblyPath, args.Name));
}
return null;
}
Run Code Online (Sandbox Code Playgroud)