Is there something like:
AppDomain.CurrentDomain.GetAssemblyByName(\"TheAssemblyName\")
so instead of looping through AppDomain.Curre
I resolved with LINQ
Assembly GetAssemblyByName(string name)
{
return AppDomain.CurrentDomain.GetAssemblies().
SingleOrDefault(assembly => assembly.GetName().Name == name);
}
Have a look at the System.Reflection.Assembly class, in particular the Load method: MSDN
If this is an assembly you have referenced, I like to write a class like the following:
namespace MyLibrary {
public static class MyLibraryAssembly {
public static readonly Assembly Value = typeof(MyLibraryAssembly).Assembly;
}
}
and then whenever you need a reference to that assembly:
var assembly = MyLibraryAssembly.Value;
It depends on what you're trying to accomplish.
If you just want to get the assembly, then you should call System.Reflection.Assembly.Load()
(as already pointed out). That's because .NET automatically checks if the assembly has already been loaded into the current AppDomain and doesn't load it again if it has been.
If you're just trying to check whether the assembly has been loaded or not (for some diagnostics reason, perhaps) then you do have to loop over all the loaded assemblies.
Another reason you might want to loop is if you know only some of the assembly information (eg. you're not sure of the version). That is, you know enough to "recognise it when you see it", but not enough to load it. That is a fairly obscure and unlikely scenario, though.
Have you tried looking at Assembly.Load(...)?
You can write an extension method that does what you need.
This method will only enumerate loaded assemblies, if you possibly need to load it, use Assembly.Load
from the accepted answer.
public static class AppDomainExtensions
{
public static Assembly GetAssemblyByName(this AppDomain domain, string assemblyName)
{
return domain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == assemblyName);
}
}
Then you call this method on an AppDomain like this:
Assembly a = AppDomain.CurrentDomain.GetAssemblyByName("SomeAssembly")
If SomeAssembly is loaded into the current AppDomain the method will return it, otherwise it will return null
.