Assembly.Load()具有名称'的重复类型'

时间:2016-04-24 17:54:01

标签: c# .net

使用Assembly.Load()函数从内存中获取.NET EXE文件,但是当我将我的字节数组提供给此函数时,我在程序集中得到一个名为...的BadImageFomatException重复类型。

enter image description here

我的代码是:

try{
                    // prepare the Form to show balloontip
                    frmDefault frm = new frmDefault();

                    // prepare to load the application into memory (using Assembly.Load)

                    // read the bytes from the application exe file
                    FileStream fs = new FileStream(filePath, FileMode.Open);
                    BinaryReader br = new BinaryReader(fs);
                    byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
                    fs.Close();
                    br.Close();

                    // load the bytes into Assembly
                    Assembly a = Assembly.Load(bin);
                    // search for the Entry Point
                    MethodInfo method = a.EntryPoint;
                    if (method != null)
                    {

                        // create an istance of the Startup form Main method
                        object o = a.CreateInstance(method.Name);
                        Console.Write("Application started!");
                        method.Invoke(o, null);

                    }
                    else
                    {
                        // impossible to launch the application
                        Console.Write("Application error!");
                    }
                }
                catch
                {

                }

1 个答案:

答案 0 :(得分:0)

首先:

 // read the bytes from the application exe file
 FileStream fs = new FileStream(filePath, FileMode.Open);
 BinaryReader br = new BinaryReader(fs);
 byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
 fs.Close();
 br.Close();

 // load the bytes into Assembly
 Assembly a = Assembly.Load(bin);

可替换为:

var a = Assembly.LoadFile(filePath);

关于这个问题,似乎你正在从同一个二进制文件中加载2个不同的版本。从您加载文件的位置加倍。