从资源运行EXE时出错



我有两个WinForms . NET应用程序"Test.exe",其中资源"WindowsFormsApplication1.exe"。资源被标记为"嵌入"。程序资源空白项目Winforms(只有窗体和一个没有处理程序的按钮)。在"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
        }

当尝试从资源中运行EXE时出现错误:"TargetInvocationException"

 exeAssembly.EntryPoint.Invoke(null, null);

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

    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
        }

我应该更小心。))

相关内容

  • 没有找到相关文章

最新更新