jsirr13
jsirr13

Reputation: 1002

Check if Assembly Exists by name before loading it

I want to take this:

try
{
    Assembly assembly = Assembly.Load("This.Is.My.Assembly.Name");
}
catch (Exception)
{
}

And do something similar, but instead never have it throw an exception. Perhaps do something that gets null back instead of an exception, checking if the assembly exists before even attempting to load it. What's the most elegant way to accomplish this?

Upvotes: 2

Views: 4809

Answers (4)

bgh
bgh

Reputation: 2120

What worked in my case was to simply check if the assembly's dll file exists in the current working directory:

if (File.Exists(assemblyName + ".dll"))
{
    Assembly.Load(assemblyName);
}
else
{
    // Fall-back logic.
}

It's important to note that whereas the assembly's file name will usually be the assembly name followed by the "dll" extension, this is not always the case. For the assemblies that I needed to be loaded this way, I knew it will be the case.

Upvotes: 2

Hamed Nikzad
Hamed Nikzad

Reputation: 658

You can Check assembly like this:

bool IsAssemblyExists(string assemblyName)
{
    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
    {
       if (assembly.FullName.StartsWith(assemblyName))
          return true;
    }
    return false;
}

Upvotes: 2

Toni Wenzel
Toni Wenzel

Reputation: 2091

You can use Assembly.ReflectionOnlyLoad to try to get the Assembly. See http://msdn.microsoft.com/de-de/library/0et80c7k(v=vs.110).aspx . If the assembly won't be found and an exception is raised, but if it was found then the assembly is not loaded to your AppDomain. You can see it as "TryLoadAssembly". ;)

Upvotes: 1

hawkstrider
hawkstrider

Reputation: 4341

You can check to see if the executing assembly has a reference to your assembly. Something like this.

if (Assembly.GetExecutingAssembly().GetReferencedAssemblies()
                .FirstOrDefault(c => c.FullName == "This.Is.My.Assembly.Name") == null)
{
    var assembly = Assembly.Load("This.Is.My.Assembly.Name");
}

Upvotes: 0

Related Questions