CodeDom: compile a partial class

I am trying to compile code in a text file to change the value in a TextBox in the main form of a WinForms application. I.e. add another partial class with the method to the calling form. The form has one button (button1) and one TextBox (textBox1).

Code in a text file:

this.textBox1.Text = "Hello World !!";

And the code:

namespace WinFormCodeCompile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Load code from file
            StreamReader sReader = new StreamReader(@"Code.txt");
            string input = sReader.ReadToEnd();
            sReader.Close();

            // Code literal
            string code =
                @"using System;
                  using System.Windows.Forms;

                  namespace WinFormCodeCompile
                  {
                      public partial class Form1 : Form
                      {

                           public void UpdateText()
                           {" + input + @"
                           }
                       }
                   }";

            // Compile code
            CSharpCodeProvider cProv = new CSharpCodeProvider();
            CompilerParameters cParams = new CompilerParameters();
            cParams.ReferencedAssemblies.Add("mscorlib.dll");
            cParams.ReferencedAssemblies.Add("System.dll");
            cParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cParams.GenerateExecutable = false;
            cParams.GenerateInMemory = true;

            CompilerResults cResults = cProv.CompileAssemblyFromSource(cParams, code);

            // Check for errors
            if (cResults.Errors.Count != 0)
            {
                foreach (var er in cResults.Errors)
                {
                    MessageBox.Show(er.ToString());
                }
            }
            else
            {
                // Attempt to execute method.
                object obj = cResults.CompiledAssembly.CreateInstance("WinFormCodeCompile.Form1");
                Type t = obj.GetType();
                t.InvokeMember("UpdateText", BindingFlags.InvokeMethod, null, obj, null);
            }


        }
    }
}

When I compile the code, CompilerResults returns an error that says WinFormCodeCompile.Form1 does not contain a definition for textBox1.

Is there a way to dynamically create another partial class file for the calling assembly and execute this code?

I suppose I am missing something really simple.

+3
source share
2

- , ( CLR).

+5

, , :

// etc
public void UpdateText(object passBox)
{" + input + @" }
// more etc
t.InvokeMember("UpdateText", BindingFlags.InvokeMethod, null, obj, new object[] { this.textbox });

, :

(passBox as TextBox).Text = "Hello World!!";
+1

Source: https://habr.com/ru/post/1742565/


All Articles