您的位置:首页 > 编程语言 > C#

动态加载DLL(C#)

2012-04-23 08:52 351 查看
public class PlugingManager
{
//插件装载器
public ArrayList Plugins = new ArrayList();
//插件FullName
public ArrayList PlugFullName = new ArrayList();
//插件类型
public ArrayList PlugTypes = new ArrayList();

#region 构造函数
/// <summary>
/// PlugingManager插件加载
/// </summary>
/// <param name="plugspath">插件所在目录必须是运行目录中的文件夹</param>
/// <param name="StartsWith">加载指定插件(插件包含的名称)</param>
/// <param name="InterfaceName">插件接口名称</param>
public PlugingManager(string plugspath,string StartsWith,string InterfaceName)
{
//获取插件目录(plugins)下所有文件
string[] files = Directory.GetFiles(Application.StartupPath + @"\\" + plugspath);

foreach (string file in files)
{
if (file.ToUpper().EndsWith(StartsWith.ToUpper()))
{
try
{
//Assembly ab = Assembly.LoadFrom(file);
Assembly ab = null;

//先将插件拷贝到内存缓冲
byte[] addinStream = null;
using(FileStream input = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
BinaryReader reader = new BinaryReader(input);
addinStream = reader.ReadBytes((int) input.Length);

}
ab = Assembly.Load(addinStream); //加载内存中的Dll
Type[] types = ab.GetTypes();
foreach (Type t in types)
{
if (t.GetInterface(InterfaceName) != null)
{
Plugins.Add(ab.CreateInstance(t.FullName));
PlugFullName.Add(t.FullName);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
#endregion
} PlugingManager plug = new PlugingManager("Plugs", "Garden.Plugs.dll", "IPlug");

var win = plug.Plugins.ToArray().FirstOrDefault(m => ((Type)m.GetType()).Name.ToLower() == this.Tag.ToString().ToLower());
MethodInfo OnShowDlg = ((Type)win.GetType()).GetMethod("ShowSelf");
Form cl = (Form)OnShowDlg.Invoke(win, null);
cl.WindowState = FormWindowState.Maximized;
cl.MdiParent = this;
cl.Show();
foreach (object obj in plug.Plugins)
{

Type t = obj.GetType();
MethodInfo OnShowDlg = t.GetMethod("ShowSelf");
Control cl = (Control)OnShowDlg.Invoke(obj, null);

Control con = GetControlFromForm(t.Name, this);
if (con != null)
{
con.Controls.Add(cl);
cl.Dock = DockStyle.Fill;
isbreak = false;
con = null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: