-1

我正在编写一个应用程序,其中我需要所有 commandId 的集合。这些存在于多个 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 以外的文件。

4

2 回答 2

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;
       }

     }
于 2013-01-09T09:51:10.790 回答
0

尝试使用Directory.GetFiles. 之后,根据http://msdn.microsoft.com/en-us/library/ms173100.aspx确定程序集并为每个程序集使用您的方法。

于 2013-01-09T09:54:29.663 回答