Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute c# code at runtime from code file

I have a WPF C# application that contains a button.

The code of the button click is written in separate text file which will be placed in the applications runtime directory.

I want to execute that code placed in the text file on the click of the button.

Any idea how to do this?

like image 656
Vinod Maurya Avatar asked Nov 15 '10 05:11

Vinod Maurya


People also ask

What is C execute?

Execution FlowThe preprocessor generates an expanded source code. 2) Expanded source code is sent to compiler which compiles the code and converts it into assembly code. 3) The assembly code is sent to assembler which assembles the code and converts it into object code. Now a simple. obj file is generated.

Can I run C in CMD?

We usually use a compiler with a graphical user interface, to compile our C program. This can also be done by using cmd. The command prompt has a set of steps we need to perform in order to execute our program without using a GUI compiler.

Can we run C program online?

C Language online compilerWrite, Run & Share C Language code online using OneCompiler's C online compiler for free. It's one of the robust, feature-rich online compilers for C language, running the latest C version which is C18. Getting started with the OneCompiler's C editor is really simple and pretty fast.


1 Answers

Code sample for executing compiled on fly class method:

using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.IO; using System.Reflection; using System.Net; using Microsoft.CSharp; using System.CodeDom.Compiler;  namespace ConsoleApplication2 {     class Program     {         static void Main(string[] args)         {             string source =             @" namespace Foo {     public class Bar     {         public void SayHello()         {             System.Console.WriteLine(""Hello World"");         }     } }             ";               Dictionary<string, string> providerOptions = new Dictionary<string, string>                 {                     {"CompilerVersion", "v3.5"}                 };             CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);              CompilerParameters compilerParams = new CompilerParameters                 {GenerateInMemory = true,                  GenerateExecutable = false};              CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);              if (results.Errors.Count != 0)                 throw new Exception("Mission failed!");              object o = results.CompiledAssembly.CreateInstance("Foo.Bar");             MethodInfo mi = o.GetType().GetMethod("SayHello");             mi.Invoke(o, null);         }     } } 
like image 129
acoolaum Avatar answered Oct 19 '22 06:10

acoolaum