Loads specific assembly into internal list of assemblies. - CSharp System.Reflection

CSharp examples for System.Reflection:Assembly

Description

Loads specific assembly into internal list of assemblies.

Demo Code


using System.Collections.Generic;
using System.Reflection;
using System.IO;//from w  ww  . ja  v a  2  s.  com
using System;

public class Main{
        /// <summary>
        /// Loads specific assembly into internal list of assemblies.
        /// </summary>
        /// <param name="directory">Directory <c>filename</c> is relative to, or <c>null</c> if <c>filename</c> is absolute or relative to current directory.</param>
        /// <param name="filename">Relative or absolute path to assembly.</param>
        /// <remarks>See <see cref="Utils.GetFileInfo">Utils.GetFileInfo</see> for more info about how
        /// specified file is searched. If file isn't found, method tries to
        /// load assembly from global assembly cache (GAC).</remarks>
        public static Assembly LoadAssembly(string directory, string filename)
        {
            Assembly assembly;

            FileInfo assemblyFileInfo = GetFileInfo(directory, filename);

            // if assemby file exists, try to load it
            if (assemblyFileInfo.Exists)
            {
                assembly = Assembly.LoadFrom(assemblyFileInfo.FullName);
            }
            else
            {
                // if file doesn't exist, try to load assembly from GAC
                try
                {
                    assembly = Assembly.Load(filename);
                }
                catch (Exception e)
                {
                    throw (new Exception("Assembly cannot be loaded (CurrentDirectory='" + Directory.GetCurrentDirectory() + "', Name='" + filename + "')", e));
                }
            }

            // add assembly to list of assemblies only if not already present
            foreach (AssemblyItem assemblyItem in _assemblies)
                if (0 == String.Compare(assemblyItem.fullName, assembly.FullName, true))
                    return assembly;

            AssemblyItem newItem = new AssemblyItem();
            newItem.assembly = assembly;
            newItem.fullName = assembly.FullName;
            newItem.fileInfo = assemblyFileInfo;
            _assemblies.Add(newItem);
            return assembly;
        }
}

Related Tutorials