我有这样的功能
public void SetOperationDropDown()
{
cmbOperations.DataSource = PluginManager.GetAllPlugins();
if(cmbOperations.Items.Count > 0)
{
cmbOperations.SelectedItem = cmbOperations.Items[0];
}
}
此函数应获取所有dll的名称
public class PluginManager
{
/// <summary>
/// This function gets the name of the plugins and return that in a List<string>.
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public static List<string> GetAllPlugins()
{
DirectoryInfo objDirectoryInfo = new DirectoryInfo("Plugins");
FileInfo[] args = objDirectoryInfo.GetFiles("*.dll");
List<string> assemblyNames = new List<string>();
Assembly[] oAssemblies = new Assembly[args.Length];
for(int assemblyCount = 0;assemblyCount < args.Length;assemblyCount++)
{
string executablePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
oAssemblies[assemblyCount] = Assembly.LoadFile(executablePath.Remove(0,6) + "\\Plugins\\" + args[assemblyCount].Name);
try
{
foreach(Type oType in oAssemblies[assemblyCount].GetTypes())
{
// Check whether class is inheriting from IMFDBAnalyserPlugin.
if(oType.GetInterface("IMFDBAnalyserPlugin") == typeof(IMFDBAnalyserPlugin))
{
assemblyNames.Add(args[assemblyCount].Name.Substring(args[assemblyCount].Name.LastIndexOf("\\") + 1));
}
}
}
catch(Exception ex)
{
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
}
// Passing data one application domain to another.
AppDomain.CurrentDomain.SetData("AssemblyNames", assemblyNames.ToArray());
return assemblyNames;
}
并且应该在此处返回的下拉列表中填充
//Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions.
string assemblyName = Convert.ToString(cmbOperations.SelectedValue);
Assembly assembly = Assembly.LoadFrom(assemblyName);
int fileExtensionPos = assemblyName.LastIndexOf(".");
string fileName = assemblyName.Substring(0, fileExtensionPos);
Type localType = assembly.GetType(fileName + "." + fileName);
但它不是通过这种方式创建每个dll
Type localType = assembly.GetType(fileName + "." + fileName);
我需要在下拉列表中加载完整的dll列表。
我哪里错了???
答案 0 :(得分:1)
你知道它不起作用吗? “args”变量是否包含任何内容?我怀疑你的问题是你构建路径的方式。您应该使用Path类,而不是字符串操作。
获取当前的可执行文件目录:
string executablePath = Path.GetDirectoryName(Application.ExecutablePath);
您应该使用它来在GetAllPlugins()方法的开头构建DirectoryInfo。 使用子文件夹构建路径:
string pluginPath = Path.Combine(executablePath, "Plugin");
获取插件子目录中具有dll扩展名的所有文件:
string[] pluginFiles = Directory.GetFiles(pluginPath, "*.dll");
请注意,返回的文件名包含整个路径。你不需要附加任何东西:
foreach (string fileName in pluginFiles)
{
Assembly assembly = Assembly.LoadFrom(fileName);
List<Type> types = assembly.GetTypes().ToList();
foreach (Type type in types.FindAll(t => t.GetInterface("IMFDBAnalyserPlugin") != null)
{
...
}
}
应该有用。
另外,不要使用substring,如果你想要文件名,无论是否有扩展名,你都应该使用Path.GetFileName或Path.GetFileNameWithoutExtension。
并使用此方法实例化您的插件: http://msdn.microsoft.com/en-us/library/wccyzw83.aspx