compiling assembly from the other just compiled as

2019-07-07 18:53发布

问题:

I need to compile assembly in memory, that can compile another one. There is a form with one button. Here is a code of the form

using System;
using System.IO;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.CSharp;

namespace testC
{
    public partial class Form1 : Form
    {static string str_tb;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openkubik();
        }
        private void openkubik()
        {
            Thread th = new Thread(new ThreadStart(sborkakub));
            th.Start();
        }

        private void sborkakub()
        {
            System.Security.Policy.Evidence evi = AppDomain.CurrentDomain.Evidence;
            AppDomain assemblyDomain;
            AppDomainSetup assemblyDomainSetup = new AppDomainSetup();
            assemblyDomainSetup.ApplicationBase = System.Environment.CurrentDirectory;
            assemblyDomainSetup.DisallowBindingRedirects = false;
            assemblyDomainSetup.DisallowCodeDownload = true;
            assemblyDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            assemblyDomainSetup.LoaderOptimization = LoaderOptimization.MultiDomainHost;
            assemblyDomain = AppDomain.CreateDomain("AssemblyDomain", evi, assemblyDomainSetup);
            assemblyDomain.DoCallBack(assamblykub);
        }

        private static void assamblykub() {
        createtext();
        System.CodeDom.Compiler.CodeDomProvider objCodeCompiler = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
        System.CodeDom.Compiler.CompilerParameters objCompilerParameters = new System.CodeDom.Compiler.CompilerParameters();
            foreach (System.Reflection.Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) {
            objCompilerParameters.ReferencedAssemblies.Add(asm.Location);
        }
        objCompilerParameters.CompilerOptions = "/target:winexe";
        objCompilerParameters.GenerateExecutable = true;
        objCompilerParameters.GenerateInMemory = true;
        objCompilerParameters.IncludeDebugInformation = false;
        System.CodeDom.Compiler.CompilerResults objCompileResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, str_tb);
        if (objCompileResults.Errors.HasErrors) {
            MessageBox.Show(String.Format("Error: Line>{0}, {1} # {2}", objCompileResults.Errors[0].Line, objCompileResults.Errors[0].ErrorText, objCompileResults.Errors[0].ErrorNumber));
            return;
        }
        System.Reflection.Assembly objAssembly = objCompileResults.CompiledAssembly;
        object objTheClass = objAssembly.CreateInstance("MainClass");
        if ((objTheClass == null)) {
            MessageBox.Show("Can\'t load class...");
            return;
        }
        try {
            objTheClass.GetType().InvokeMember("Main", System.Reflection.BindingFlags.InvokeMethod, null, objTheClass, null);
        }
        catch (Exception ex) {
             MessageBox.Show(("Error:" + ex.Message));
        }
    }

        private static void createtext()
        {
            FileStream tempfile = new FileStream((Application.StartupPath + "/temp_open.txt"), FileMode.Open, FileAccess.Read);
            StreamReader tempfilesr = new StreamReader(tempfile, System.Text.Encoding.GetEncoding(1251));
            str_tb = tempfilesr.ReadToEnd();
            tempfilesr.Close();
            tempfile.Close();
            tempfile = null;
            tempfilesr = null;
        }
    }
}

And the code of "temp_open.txt" file

using System;
using System.IO;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


    public partial class MainClass : MarshalByRefObject
    {
public static void Main()
{
             Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
}
}
    public class Form1 : Form
    {static string str_tb;
        private System.ComponentModel.IContainer components = null;

        private System.Windows.Forms.Button button1;

           protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            this.button1.Location = new System.Drawing.Point(45, 44);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(313, 52);
            this.button1.TabIndex = 0;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(425, 143);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
 }
      public Form1()
        {    
           InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openkubik();
        }
        private void openkubik()
        {
            Thread th = new Thread(new ThreadStart(sborkakub));
            th.Start();
        }

        private void sborkakub()
        {
            System.Security.Policy.Evidence evi = AppDomain.CurrentDomain.Evidence;
            AppDomain assemblyDomain;
            AppDomainSetup assemblyDomainSetup = new AppDomainSetup();
            assemblyDomainSetup.ApplicationBase = System.Environment.CurrentDirectory;
            assemblyDomainSetup.DisallowBindingRedirects = false;
            assemblyDomainSetup.DisallowCodeDownload = true;
            assemblyDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            assemblyDomainSetup.LoaderOptimization = LoaderOptimization.MultiDomainHost;
            assemblyDomain = AppDomain.CreateDomain("AssemblyDomain", evi, assemblyDomainSetup);
            assemblyDomain.DoCallBack(assamblykub);
        }

        private static void assamblykub() {
        createtext();
        System.CodeDom.Compiler.CodeDomProvider objCodeCompiler = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
        System.CodeDom.Compiler.CompilerParameters objCompilerParameters = new System.CodeDom.Compiler.CompilerParameters();
            foreach (System.Reflection.Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) {
            objCompilerParameters.ReferencedAssemblies.Add(asm.Location);
        }
        objCompilerParameters.CompilerOptions = "/target:winexe";
        objCompilerParameters.GenerateExecutable = true;
        objCompilerParameters.GenerateInMemory = true;
        objCompilerParameters.IncludeDebugInformation = false;
        System.CodeDom.Compiler.CompilerResults objCompileResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, str_tb);
        if (objCompileResults.Errors.HasErrors) {
            MessageBox.Show(String.Format("Error: Line>{0}, {1} # {2}", objCompileResults.Errors[0].Line, objCompileResults.Errors[0].ErrorText, objCompileResults.Errors[0].ErrorNumber));
            return;
        }
        System.Reflection.Assembly objAssembly = objCompileResults.CompiledAssembly;
        object objTheClass = objAssembly.CreateInstance("MainClass");
        if ((objTheClass == null)) {
            MessageBox.Show("Can\'t load class...");
            return;
        }
        try {
            objTheClass.GetType().InvokeMember("Main", System.Reflection.BindingFlags.InvokeMethod, null, objTheClass, null);
        }
        catch (Exception ex) {
             MessageBox.Show(("Error:" + ex.Message));
        }
    }

        private static void createtext()
        {
            FileStream tempfile = new FileStream((Application.StartupPath + "/temp_open.txt"), FileMode.Open, FileAccess.Read);
            StreamReader tempfilesr = new StreamReader(tempfile, System.Text.Encoding.GetEncoding(1251));
            str_tb = tempfilesr.ReadToEnd();
            tempfilesr.Close();
            tempfile.Close();
            tempfile = null;
            tempfilesr = null;
        }
}

When I click Button1 in first form -> appears second form. but when I click Button 1 in the second form I have an FileNotFound Exception. What am I doing wrong?

回答1:

Very vague sample...
Why you are trying to call assamblykub() with assemblyDomain.DoCallBack(assamblykub);??? this approach for crossdomain calls.
Just replcae assemblyDomain.DoCallBack(assamblykub); with assamblykub() and youll get it run)



标签: c# .net codedom