views:

77

answers:

2
+1  Q: 

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 = Assembly.Load(bytes);
        exeAssembly.EntryPoint.Invoke(null, null);
    }
+1  A: 

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

Xaqron
+1 My assumption is the same: you're experiencing a common error in an uncommon scenario. Also check stackoverflow for answers to the problem of winforms threading. Likely you'll find something appropriate.
John K
+3  A: 

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!

Homam