使用反射从bin文件夹加载多个dll

时间:2013-01-09 09:42:43

标签: c# reflection dll

我正在编写一个应用程序,我需要所有commandIds的集合。这些存在于多个dll中。我可以访问bin文件夹。

我使用了反射,并且能够一次为一个dll执行此操作

Assembly a = System.Reflection.Assembly.LoadFrom(@"T:\Bin\Commands.dll");

IEnumerable<Type> types = Helper.GetLoadableTypes(a);
foreach (Type type in types)
{
    FieldInfo ID = type.GetField("ID");

    if (ID != null)
    {
        string fromValue = (ID.GetRawConstantValue().ToString());

        ListFromCSFiles.Add(fromValue);
    }
}

我的问题是我需要从所有dll获取所有ID。 Bin文件夹也包含dll以外的文件。

2 个答案:

答案 0 :(得分:2)

听起来你只需要遍历目录中的dll。

您还需要确保没有加载已加载的程序集。

例如:

  string bin = "c:\YourBin";

    DirectoryInfo oDirectoryInfo = new DirectoryInfo( bin );

    //Check the directory exists
    if ( oDirectoryInfo.Exists )
    {
       //Foreach Assembly with dll as the extension
       foreach ( FileInfo oFileInfo in oDirectoryInfo.GetFiles( "*.dll", SearchOption.AllDirectories ) )
       {

                        Assembly tempAssembly = null;

                        //Before loading the assembly, check all current loaded assemblies in case talready loaded
                        //has already been loaded as a reference to another assembly
                        //Loading the assembly twice can cause major issues
                        foreach ( Assembly loadedAssembly in AppDomain.CurrentDomain.GetAssemblies() )
                        {
                            //Check the assembly is not dynamically generated as we are not interested in these
                            if ( loadedAssembly.ManifestModule.GetType().Namespace != "System.Reflection.Emit" )
                            {
                                //Get the loaded assembly filename
                                string sLoadedFilename =
                                    loadedAssembly.CodeBase.Substring( loadedAssembly.CodeBase.LastIndexOf( '/' ) + 1 );

                                //If the filenames match, set the assembly to the one that is already loaded
                                if ( sLoadedFilename.ToUpper() == oFileInfo.Name.ToUpper() )
                                {
                                    tempAssembly = loadedAssembly;
                                    break;
                                }
                            }
                        }

                        //If the assembly is not aleady loaded, load it manually
                        if ( tempAssembly == null )
                        {
                            tempAssembly = Assembly.LoadFile( oFileInfo.FullName );
                        }

                        Assembly a = tempAssembly;
       }

     }

答案 1 :(得分:0)

尝试使用Directory.GetFiles获取目录的所有文件。 之后,根据http://msdn.microsoft.com/en-us/library/ms173100.aspx,确定程序集并使用您的方法进行每个程序集。