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