Execute C# Code at Runtime from Code File

execute c# code at runtime from code file

You can use Microsoft.CSharp.CSharpCodeProvider to compile code on-the-fly. In particular, see CompileAssemblyFromFile.

Is it possible to dynamically compile and execute C# code fragments?

The best solution in C#/all static .NET languages is to use the CodeDOM for such things. (As a note, its other main purpose is for dynamically constructing bits of code, or even whole classes.)

Here's a nice short example take from LukeH's blog, which uses some LINQ too just for fun.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

class Program
{
static void Main(string[] args)
{
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
@"using System.Linq;
class Program {
public static void Main(string[] args) {
var q = from i in Enumerable.Range(1,100)
where i % 2 == 0
select i;
}
}");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
}
}

The class of primary importance here is the CSharpCodeProvider which utilises the compiler to compile code on the fly. If you want to then run the code, you just need to use a bit of reflection to dynamically load the assembly and execute it.

Here is another example in C# that (although slightly less concise) additionally shows you precisely how to run the runtime-compiled code using the System.Reflection namespace.

C# Use comment when compiling and running code from path at runtime

Each element given to CompileAssemblyFromSource is supposed to be a file, not a single line of code. So read the whole file into a single string and give it to the method and it'll work just fine.

static void Main(string[] args)
{
var code = System.IO.File.ReadAllText(@"C:\program.txt");
CompileAndRun(code);

Console.ReadKey();
}

static void CompileAndRun(string code)
{
CompilerParameters CompilerParams = new CompilerParameters();
string outputDirectory = Directory.GetCurrentDirectory();

CompilerParams.GenerateInMemory = true;
CompilerParams.TreatWarningsAsErrors = false;
CompilerParams.GenerateExecutable = false;
CompilerParams.CompilerOptions = "/optimize";

string[] references = { "System.dll" };
CompilerParams.ReferencedAssemblies.AddRange(references);

CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams, code);
// ...
}

(C#) Compiling class at runtime and calling methods from original code

Adding a reference to the current assembly solved the problem:

CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
//The next line is the addition to the original code
parameters.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location);

More about:
Compiling c# at runtime with user defined functions

C# How to add a code to execute at Runtime

Searched for 'dynamic c# code execution' and Google came up with this blog from 2002... This might work for you..

http://www.west-wind.com/presentations/dynamiccode/dynamiccode.htm

The article refers to System.CodeDom.Compiler to compile a assembly on the fly and then using Reflection to execute that code. Sounds like fun ;)

EDIT: As DaveL suggested: Is it possible to dynamically compile and execute C# code fragments?

Codegeneration at runtime from a string to console exe is not working in C# .NET6

It is not possible to codegenerate directly a console application like the initial approach above. One possible solution is to generate first a dll (what I mentioned above in the example code is working fine), and from there include that .dll into a .exe, from where the functionality can run.

Is it possible to create/execute code in run-time in C#?

Absolutely - that's exactly what I do for Snippy for example, for C# in Depth. You can download the source code here - it uses CSharpCodeProvider.

There's also the possibility of building expression trees and then compiling them into delegates, using DynamicMethod, or the DLR in .NET 4... all kinds of things.



Related Topics



Leave a reply



Submit