vb.net running a exe in memory

2019-07-21 22:33发布

I'm trying to run a app on memory but I'm having error at Invoke. What am I doing wrong?

I'm trying to do this but in vb.net

Code C#

 // 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);
    // invoke the application starting point
    method.Invoke(o, null);
}

in vb:

Dim instance As FileStream = File.Open("teste.exe", FileMode.Open)
Dim br As New BinaryReader(instance)
Dim bin As Byte() = br.ReadBytes(Convert.ToInt32(instance.Length))
instance.Close()
br.Close()
Dim a As Assembly = Assembly.Load(bin)
Dim metodo As MethodInfo = a.EntryPoint
If (IsDBNull(metodo) = False) Then
    'create an istance of the Startup form Main method
    Dim o As Object = a.CreateInstance(metodo.Name)
    'invoke the application starting point
    metodo.Invoke(o, Nothing)
Else
    MessageBox.Show("Nao encontrado")
End If

UPDATE:

I found the answer. I created the "test.exe" like a ConsoleAplication, than in the module I code

Imports System.Windows.Forms
Module Module1
    Sub Main()
        Dim Form1 As New Form1
        Form1.Show()
        Do Until Form1.Visible = False
            Application.DoEvents()
        Loop
    End Sub
End Module

Then I changed from ConsoleApplication to Windowsform And create my Form1. And this

metodo.Invoke(o, Nothing)

to this:

metodo.Invoke(Nothing, New Object() {})

Thank you guys for the support!

标签: vb.net memory
2条回答
我只想做你的唯一
2楼-- · 2019-07-21 23:07

Assuming the c# code works you mistranslated the null check.

The equivalent of 'if (method != null)' in vb.net is

If method IsNot Nothing Then
    Dim o = a.CreateInstance(method.Name)
    method.Invoke(o, Nothing)
End If
查看更多
Ridiculous、
3楼-- · 2019-07-21 23:22

The Main method expects that you pass it the args parameter. Your current call is not passing any parameters, so I'm expecting that you are getting the following error if it ever reaches that line:

System.Reflection.TargetParameterCountException: Parameter count mismatch.

To fix it, just pass a one-element object array as the second parameter of the method.Invoke. Also, because the Main method is a static method, you don't need to do a CreateInstance before invoking the method.

So all you need is this:

metodo.Invoke(Nothing, New Object() {Nothing})

If, for some reason, you actually need pass values to the main's args parameter, you can do it like this:

metodo.Invoke(Nothing, New Object() {New String() {"param1", "param2"}})
查看更多
登录 后发表回答