Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How to execute c# statment in a string?(Compiling and Running code at runtime)

How to execute c# statment in a string?(Compiling and Running code at runtime)

Scheduled Pinned Locked Moved C#
tutorialcsharphelpquestion
10 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    jojoba2011
    wrote on last edited by
    #1

    I'm trying to find the way how to execute a string contain c# code.

    Example

    string st = "if (textBox1.Text == "Jon" && chkText.Checked)
    MessageBox.Show("Yes!");
    else
    MessageBox.Show(textBox1.Text);";

    I want to execute st then i want to see the result in a message box.

    Please kindly help me. Thank in advance!

    L T U 3 Replies Last reply
    0
    • J jojoba2011

      I'm trying to find the way how to execute a string contain c# code.

      Example

      string st = "if (textBox1.Text == "Jon" && chkText.Checked)
      MessageBox.Show("Yes!");
      else
      MessageBox.Show(textBox1.Text);";

      I want to execute st then i want to see the result in a message box.

      Please kindly help me. Thank in advance!

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      http://support.microsoft.com/kb/304655[^] I'd recommend against putting the MessageBox and references in your textbox there; a simple check whether the text passed as an argument would suffice. The advantage being that there's no reference from the compiled code to your UI.

      Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

      J 1 Reply Last reply
      0
      • J jojoba2011

        I'm trying to find the way how to execute a string contain c# code.

        Example

        string st = "if (textBox1.Text == "Jon" && chkText.Checked)
        MessageBox.Show("Yes!");
        else
        MessageBox.Show(textBox1.Text);";

        I want to execute st then i want to see the result in a message box.

        Please kindly help me. Thank in advance!

        T Offline
        T Offline
        turbosupramk3
        wrote on last edited by
        #3

        When I'm debugging, I do the following

        string st = something

        if (textBox1.Text == "Jon" && chkText.Checked)
        MessageBox.Show(st + " (if)");
        else
        MessageBox.Show(st + " (else)");"

        C 1 Reply Last reply
        0
        • L Lost User

          http://support.microsoft.com/kb/304655[^] I'd recommend against putting the MessageBox and references in your textbox there; a simple check whether the text passed as an argument would suffice. The advantage being that there's no reference from the compiled code to your UI.

          Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

          J Offline
          J Offline
          jojoba2011
          wrote on last edited by
          #4

          thanks but i get error. Can u give me a small example!

          L 1 Reply Last reply
          0
          • J jojoba2011

            thanks but i get error. Can u give me a small example!

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #5

            jojoba2011 wrote:

            thanks but i get error.
             
            Can u give me a small example!

            If you'd get an error, it'd be more helpfull to solve that, than blindly trying examples. I'm guessing that it's due to the fact that you only have the body of a method in there; just like in Visual Studio, the code needs to be located in a class. Try the example below in a console-application.

            using System;
            using System.CodeDom.Compiler;
            using System.Diagnostics;
            using System.IO;
            using System.Reflection;
            using Microsoft.CSharp;

            class Program
            {
            static void Main(string[] args)
            {
            string sources = @"
            using System;
            public static class ExampleClass
            {
            public static void ExampleMethod()
            {
            Console.WriteLine(""Hello World!"");
            }
            }";

                CSharpCodeProvider codeProvider = new CSharpCodeProvider();
                string Output = "Out.dll";
            
                CompilerParameters parameters = new CompilerParameters()
                {
                    GenerateExecutable = false,
                    OutputAssembly = Output
                };
                CompilerResults results = codeProvider.CompileAssemblyFromSource(
                    parameters, sources);
            
                if (results.Errors.Count > 0)
                {
                    foreach (CompilerError CompErr in results.Errors)
                    {
                        Console.WriteLine(
                                    "Line number " + CompErr.Line +
                                    ", Error Number: " + CompErr.ErrorNumber +
                                    ", '" + CompErr.ErrorText + ";");
                    }
                }
                else
                {
                    // successfull compile, try to load what we just compiled
                    Assembly myAssembly = Assembly.Load(File.ReadAllBytes("Out.dll"));
            
                    // load the class;
                    Type myType = myAssembly.GetType("ExampleClass");
            
                    // get the method;
                    MethodInfo mi = myType.GetMethod("ExampleMethod");
            
                    // execute
                    mi.Invoke(null, null);
                }
            
                Console.WriteLine("Hit any user to continue");
                Console.ReadKey();
            }
            

            Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

            B J 2 Replies Last reply
            0
            • L Lost User

              jojoba2011 wrote:

              thanks but i get error.
               
              Can u give me a small example!

              If you'd get an error, it'd be more helpfull to solve that, than blindly trying examples. I'm guessing that it's due to the fact that you only have the body of a method in there; just like in Visual Studio, the code needs to be located in a class. Try the example below in a console-application.

              using System;
              using System.CodeDom.Compiler;
              using System.Diagnostics;
              using System.IO;
              using System.Reflection;
              using Microsoft.CSharp;

              class Program
              {
              static void Main(string[] args)
              {
              string sources = @"
              using System;
              public static class ExampleClass
              {
              public static void ExampleMethod()
              {
              Console.WriteLine(""Hello World!"");
              }
              }";

                  CSharpCodeProvider codeProvider = new CSharpCodeProvider();
                  string Output = "Out.dll";
              
                  CompilerParameters parameters = new CompilerParameters()
                  {
                      GenerateExecutable = false,
                      OutputAssembly = Output
                  };
                  CompilerResults results = codeProvider.CompileAssemblyFromSource(
                      parameters, sources);
              
                  if (results.Errors.Count > 0)
                  {
                      foreach (CompilerError CompErr in results.Errors)
                      {
                          Console.WriteLine(
                                      "Line number " + CompErr.Line +
                                      ", Error Number: " + CompErr.ErrorNumber +
                                      ", '" + CompErr.ErrorText + ";");
                      }
                  }
                  else
                  {
                      // successfull compile, try to load what we just compiled
                      Assembly myAssembly = Assembly.Load(File.ReadAllBytes("Out.dll"));
              
                      // load the class;
                      Type myType = myAssembly.GetType("ExampleClass");
              
                      // get the method;
                      MethodInfo mi = myType.GetMethod("ExampleMethod");
              
                      // execute
                      mi.Invoke(null, null);
                  }
              
                  Console.WriteLine("Hit any user to continue");
                  Console.ReadKey();
              }
              

              Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

              B Offline
              B Offline
              BillWoodruff
              wrote on last edited by
              #6

              vote => up. That's a very useful, and complete, example, thanks !

              "What Turing gave us for the first time (and without Turing you just couldn't do any of this) is he gave us a way of thinking about and taking seriously and thinking in a disciplined way about phenomena that have, as I like to say, trillions of moving parts. Until the late 20th century, nobody knew how to take seriously a machine with a trillion moving parts. It's just mind-boggling." Daniel C. Dennett

              1 Reply Last reply
              0
              • L Lost User

                jojoba2011 wrote:

                thanks but i get error.
                 
                Can u give me a small example!

                If you'd get an error, it'd be more helpfull to solve that, than blindly trying examples. I'm guessing that it's due to the fact that you only have the body of a method in there; just like in Visual Studio, the code needs to be located in a class. Try the example below in a console-application.

                using System;
                using System.CodeDom.Compiler;
                using System.Diagnostics;
                using System.IO;
                using System.Reflection;
                using Microsoft.CSharp;

                class Program
                {
                static void Main(string[] args)
                {
                string sources = @"
                using System;
                public static class ExampleClass
                {
                public static void ExampleMethod()
                {
                Console.WriteLine(""Hello World!"");
                }
                }";

                    CSharpCodeProvider codeProvider = new CSharpCodeProvider();
                    string Output = "Out.dll";
                
                    CompilerParameters parameters = new CompilerParameters()
                    {
                        GenerateExecutable = false,
                        OutputAssembly = Output
                    };
                    CompilerResults results = codeProvider.CompileAssemblyFromSource(
                        parameters, sources);
                
                    if (results.Errors.Count > 0)
                    {
                        foreach (CompilerError CompErr in results.Errors)
                        {
                            Console.WriteLine(
                                        "Line number " + CompErr.Line +
                                        ", Error Number: " + CompErr.ErrorNumber +
                                        ", '" + CompErr.ErrorText + ";");
                        }
                    }
                    else
                    {
                        // successfull compile, try to load what we just compiled
                        Assembly myAssembly = Assembly.Load(File.ReadAllBytes("Out.dll"));
                
                        // load the class;
                        Type myType = myAssembly.GetType("ExampleClass");
                
                        // get the method;
                        MethodInfo mi = myType.GetMethod("ExampleMethod");
                
                        // execute
                        mi.Invoke(null, null);
                    }
                
                    Console.WriteLine("Hit any user to continue");
                    Console.ReadKey();
                }
                

                Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                J Offline
                J Offline
                jojoba2011
                wrote on last edited by
                #7

                thanks in advanced! My question is this : Is it possible to excute code without creating any class ....?

                string sources = @"
                using System;
                public static class ExampleClass
                {
                public static void ExampleMethod()
                {
                Console.WriteLine(""Hello World!"");
                }
                }";

                and one more : How to use the textBox1.Text and other controls values?

                L 1 Reply Last reply
                0
                • T turbosupramk3

                  When I'm debugging, I do the following

                  string st = something

                  if (textBox1.Text == "Jon" && chkText.Checked)
                  MessageBox.Show(st + " (if)");
                  else
                  MessageBox.Show(st + " (else)");"

                  C Offline
                  C Offline
                  CHill60
                  wrote on last edited by
                  #8

                  Although MessageBox may have it's place in limited circumstances you may be better off using more robust debugging techniques that can be left in the finished product. Have a look at http://support.microsoft.com/kb/815788[^] and http://msdn.microsoft.com/en-us/library/system.diagnostics.debug(v=vs.110).aspx[^]

                  1 Reply Last reply
                  0
                  • J jojoba2011

                    thanks in advanced! My question is this : Is it possible to excute code without creating any class ....?

                    string sources = @"
                    using System;
                    public static class ExampleClass
                    {
                    public static void ExampleMethod()
                    {
                    Console.WriteLine(""Hello World!"");
                    }
                    }";

                    and one more : How to use the textBox1.Text and other controls values?

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #9

                    jojoba2011 wrote:

                    Is it possible to excute code without creating any class ....?

                    No. Then again, it wouldn't be much work to wrap it automatically in a class; it's just text after all. Also keep in mind that this class will not be "unloaded".

                    jojoba2011 wrote:

                    How to use the textBox1.Text and other controls values?

                    You see that using? The code one compiles needs to have a reference to your project. That means including a "using" directive in the source code, as well as adding a reference[^] to the compilerparameters. You could save a lot of pain by rewriting that part of the code to use variables/parameters, and not directly the UI-elements of your project. --edit; Alternatively, if you'd install Mono, there'd be the Eval[^] method.

                    Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                    1 Reply Last reply
                    0
                    • J jojoba2011

                      I'm trying to find the way how to execute a string contain c# code.

                      Example

                      string st = "if (textBox1.Text == "Jon" && chkText.Checked)
                      MessageBox.Show("Yes!");
                      else
                      MessageBox.Show(textBox1.Text);";

                      I want to execute st then i want to see the result in a message box.

                      Please kindly help me. Thank in advance!

                      U Offline
                      U Offline
                      User 9427106
                      wrote on last edited by
                      #10

                      i got the solution : http://stackoverflow.com/questions/14485226/convert-string-to-executable-c-sharp-code-in-code-behind Solved ! using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Microsoft.CSharp; using System.CodeDom.Compiler; using System.Reflection; namespace WindowsFormsApplication2 { public partial class Form1 : Form { private System.Windows.Forms.TextBox txtf; private System.Windows.Forms.TextBox txts; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox txt; //public Form1() //{ // InitializeComponent(); //} public Form1() { this.txtf = new System.Windows.Forms.TextBox(); this.txts = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.txt = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // txtf // this.txtf.Location = new System.Drawing.Point(81, 125); this.txtf.Name = "txtf"; this.txtf.Size = new System.Drawing.Size(100, 20); this.txtf.TabIndex = 0; // // txts // this.txts.Location = new System.Drawing.Point(81, 161); this.txts.Name = "txts"; this.txts.Size = new System.Drawing.Size(100, 20); this.txts.TabIndex = 0; // // button1 // this.button1.Location = new System.Drawing.Point(81, 196); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 1; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // txt // this.txt.Location = new System.Drawing.Point(12, 12); this.txt.Multiline = true; this.txt.Name = "txt"; this.txt.Size = new System.Drawing.Size(260, 107); this.txt.TabIndex = 0; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScal

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups