C# 使用反射从bin文件夹加载多个DLL
我正在编写一个应用程序,其中我需要所有commandid的集合。这些存在于多个DLL中。我有权访问bin文件夹 我使用反射,并且能够一次为一个dll执行此操作C# 使用反射从bin文件夹加载多个DLL,c#,reflection,dll,C#,Reflection,Dll,我正在编写一个应用程序,其中我需要所有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) {
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);
}
}
Assembly a=System.Reflection.Assembly.LoadFrom(@“T:\Bin\Commands.dll”);
IEnumerable types=Helper.GetLoadableTypes(a);
foreach(类型中的类型)
{
FieldInfo ID=type.GetField(“ID”);
如果(ID!=null)
{
字符串fromValue=(ID.GetRawConstantValue().ToString());
ListFromCSFiles.Add(fromValue);
}
}
我的问题是我需要从所有DLL获取所有ID。Bin文件夹也包含DLL以外的文件 听起来您只需要在目录中循环DLL 您还需要确保没有加载已加载的程序集 例如:
尝试使用
directory.GetFiles
获取目录的所有文件。
然后,根据,确定程序集并对每个程序集使用您的方法。那么,您为什么不解析
Bin
文件夹,按扩展名.dll
过滤文件,将它们放入for
循环中,并为每次迭代执行上面的代码呢?
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;
}
}