我想通过从字节数组加载它来启动C#控制台应用程序.
如果我将应用程序写入磁盘并手动启动程序,它会启动,因此这意味着正确读取了字节.
我尝试了在网上找到的各种片段,例如:
Assembly a = Assembly.Load(programma);
MethodInfo method = a.EntryPoint;
if (method != null)
{
object o = a.CreateInstance(method.Name);
method.Invoke(o, null);
}
要么:
public static Thread RunFromMemory(byte[] bytes)
{
var thread = new Thread(new ThreadStart(() =>
{
var assembly = Assembly.Load(bytes);
MethodInfo method = assembly.EntryPoint;
if (method != null)
{
method.Invoke(null, null);
}
}));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return thread;
}
这些代码实际上适用于Winforms应用程序,但不适用于控制台应用程序.
最佳答案 您获取程序的字节,然后可以使用Assembly.Load从这些字节加载程序集并找到EntryPoint并调用它.
private static void RunBytes(byte[] bytes)
{
Assembly exeAssembly = Assembly.Load(bytes);
var entryPoint = exeAssembly.EntryPoint;
var parms = exeAssembly?.CreateInstance(entryPoint.Name);
entryPoint?.Invoke(parms, null);
}
您可以先将磁盘写入磁盘,然后尝试使用Assembly.LoadFrom.