开发者

C# Run From Bytes

I am working on making my client open another program by downloading the bytes and using reflection to open it. I have currently got this working on a C# Console Application, but when I try and do it on a Windows Form Application I get this error.

"Exception has been thrown by the target of an invocation."

Here is the code

using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
    private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        if (listBox1.SelectedItem.ToString() != null)
        {
            if (MessageBox.Show("Run " + listBox1.SelectedItem.ToString() + "?", "Run this program?", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                byte[] bytes;
                using (WebClient client = new WebClient())
                {
                    bytes = client.DownloadData(new Uri("http://example.net/program.exe"));
                }
                RunFromBytes(bytes);
            }
        }
    }
    private static void RunFromBytes(byte[] bytes)
    {
        Assembly exeAssembly = 开发者_Go百科Assembly.Load(bytes);
        exeAssembly.EntryPoint.Invoke(null, null);
    }


You must do the following:

  1. Create a new application domain
  2. Write the byte array to a file
  3. Execute it by ExecuteAssembly

This is the code:

File.WriteAllBytes("yourApplication.exe", bytes);
AppDomain newDomain= AppDomain.CreateDomain("newDomain");
newDomain.ExecuteAssembly("file.exe");

Good luck!


That's because you are trying to access your form controls from another thread. see here: http://www.yoda.arachsys.com/csharp/threads/winforms.shtml


You can do like:

private static void RunFromBytes(byte[] bytes)
{

Assembly exeAssembly = Assembly.Load(bytes);
var entryPoint = exeAssembly.EntryPoint;
var parms = exeAssembly.CreateInstance(entryPoint.Name);
 entryPoint.Invoke(parms, null);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜