This code implements DLL dynamic loading, like the filter plugin in PS!
1. Create an interface Project class library, where the name is: Test.iplugin
using System; namespace test.iplugin{ publicinterface IPlugin { void Run ( Object obj);} }
2. Build a DLL plug-in class library project to reference the interface project ' Test.iplugin ' and implement the Run method, where the name is: Test.plugin
using System; namespace test.plugin{ publicclass Plugin:IPlugin.IPlugin { #region IPlugin member void Test.IPlugin.IPlugin.Run (object obj) { System.Windows.Forms.MessageBox.Show (obj. ToString ()); } #endregion }}
3. Plug-in dynamic loading implementation, the establishment of the console or WinForm project and reference Interface project Test.iplugin, the following is the dynamic loading code
Private voidBtnload_click (Objectsender, EventArgs e) { stringFilePath =@"file path \test.plugin.dll"; Assembly DLL=NULL; {//method One: Load directly from the DLL path (online code, native test error)//dll = Assembly.Load (FilePath); } {//method Two: Load the DLL into memory before loading it from memoryFileStream fs =NewFileStream (FilePath, FileMode.Open, FileAccess.Read); BinaryReader BR=NewBinaryReader (FS); byte[] BFile = Br. Readbytes ((int) fs. Length); Br. Close (); Fs. Close (); DLL=Assembly.Load (BFile); } //Calling Interface foreach(varTinchDLL. GetTypes ()) {if(T.getinterface ("IPlugin") !=NULL) { varPlugin =(Iplugin.iplugin) activator.createinstance (t); Plugin. Run ("Test"); } }}
The above for the implementation of the dynamic plug-in mode code, first note that the code to reduce the plug-in 2 ways
----------------Split Line---------------
Note the first method, which throws an exception when Assembly.Load (FilePath):
Failed to load file or assembly "* * *" or one of its dependencies. The given assembly name or base code is invalid. (Exception from hresult:0x80131047)
On the internet to find a lot of relevant solutions have failed to resolve this error, the development environment for VS2008, three projects are Framework2.0 X86 mode, tried the way
1. Force CPU mode to X86 2. All DLLs and EXE are placed in the same directory 3. Cancel the Enable Visual Studio host Process
Finally inadvertently see the useful way to load into memory, and then use BinaryReader read byte array reload, perfect solution.
C # implements dynamic load DLL plug-ins and hresult:0x80131047 processing