0

I have a two WinForms NET application "Test.exe" at which the resource "WindowsFormsApplication1.exe". Resource is marked as "embedded." The program resource - blank project Winforms (only form and a button without a handler). Use common code in "Test.exe":

 private void button1_Click(object sender, EventArgs e)
        {
            this.Hide();
            RunInternalExe("WindowsFormsApplication1.exe");
        }
   private static void RunInternalExe(string exeName)
        {
            //Get the current assembly
            Assembly assembly = Assembly.GetExecutingAssembly();

            //Get the assembly's root name
            string rootName = assembly.GetName().Name;

            //Get the resource stream
            Stream resourceStream = assembly.GetManifestResourceStream(rootName + "." + exeName);

            //Verify the internal exe exists
            if (resourceStream == null)
                return;

            //Read the raw bytes of the resource
            byte[] resourcesBuffer = new byte[resourceStream.Length];

            resourceStream.Read(resourcesBuffer, 0, resourcesBuffer.Length);
            resourceStream.Close();

            //Load the bytes as an assembly
            Assembly exeAssembly = Assembly.Load(resourcesBuffer);

            //Execute the assembly
            exeAssembly.EntryPoint.Invoke(null, null); //no parameters
        }

When trying to run the EXE from the resource falls out with the error: "TargetInvocationException" on the line:

 exeAssembly.EntryPoint.Invoke(null, null);
4

1 回答 1

0

我找到了解决方案。资源程序中的表单是在同一个线程中创建的。在这种情况下,我需要使用这样的代码:

    private void button1_Click(object sender, EventArgs e)
        {
        this.Hide();
        Thread t = new Thread(new ParameterizedThreadStart(RunInternalExe));
        t.Start("RunCodeFromDll.exe");

        //RunInternalExe("RunCodeFromDll.exe");
        }
    static void RunInternalExe(object tempName)
        {
        string exeName = tempName.ToString();
        //Get the current assembly
        Assembly assembly = Assembly.GetExecutingAssembly();

        //Get the assembly's root name
        string rootName = assembly.GetName().Name;

        //Get the resource stream
        Stream resourceStream = assembly.GetManifestResourceStream(rootName + "." + exeName);

        //Verify the internal exe exists
        if (resourceStream == null)
            return;

        //Read the raw bytes of the resource
        byte[] resourcesBuffer = new byte[resourceStream.Length];

        resourceStream.Read(resourcesBuffer, 0, resourcesBuffer.Length);
        resourceStream.Close();

        //Load the bytes as an assembly
        Assembly exeAssembly = Assembly.Load(resourcesBuffer);

        //Execute the assembly
        exeAssembly.EntryPoint.Invoke(null, null); //.EntryPoint.Invoke(null, null); //no parameters
        }

我应该更加小心。)))

于 2013-06-13T17:25:08.783 回答