execute c# code at runtime from code file
Asked Answered
B

5

53

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?

Bev answered 15/11, 2010 at 5:32 Comment(1)
codeproject.com/…Stalinist
S
38

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

Sullen answered 15/11, 2010 at 5:41 Comment(0)
G
99

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);
        }
    }
}
Goodness answered 15/11, 2010 at 6:7 Comment(6)
I've added in memory compilationGoodness
Post sample of your code, please. My code doesn't rise file not found exception.Goodness
I am executing the same code in a new console without any change.Bev
It's work fine for me. May you give me call stack where the exception was thrown?Goodness
It works for me in .NET 4.0 Client Profile (for both "v3.5" and "v4.0") -- I'm wondering, how would I do it with a DataContext? (i.e. the code I want to pass in is "Property >= 5 && Property < 10" and the method I would wrap it in is essentially "public object GetValue() { return " + code + " }" -- where "Property" is a property on a given datacontext...Geniality
@VinodMaurya I have noticed I get File not found if compiling fails. Do check for results.Errors.Count before trying to Invoke.Chromium
S
38

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

Sullen answered 15/11, 2010 at 5:41 Comment(0)
L
23

I recommend having a look at Microsoft Roslyn, and specifically its ScriptEngine class. Here are a few good examples to start with:

  1. Introduction to the Roslyn Scripting API
  2. Using Roslyn ScriptEngine for a ValueConverter to process user input.

Usage example:

var session = Session.Create();
var engine = new ScriptEngine();
engine.Execute("using System;", session);
engine.Execute("double Sin(double d) { return Math.Sin(d); }", session);
engine.Execute("MessageBox.Show(Sin(1.0));", session);
Limerick answered 10/11, 2012 at 12:15 Comment(1)
Before you search for the download, just use the Package-Manager: Install-Package RoslynBlackfellow
K
3

Looks like someone created a library for this called C# Eval.

EDIT: Updated link to point to Archive.org as it seems like the original site is dead.

Kareykari answered 4/2, 2014 at 20:11 Comment(1)
@RichO'Kelly, thanks - I updated it to point to the archive.org version.Kareykari
S
2

What you need is a CSharpCodeProvider Class

There are several samples to understand how does it work.

1 http://www.codeproject.com/Articles/12499/Run-Time-Code-Generation-I-Compile-C-Code-using-Mi

The important point of this example that you can do all things on flay in fact.

myCompilerParameters.GenerateExecutable = false;
myCompilerParameters.GenerateInMemory = false;

2 http://www.codeproject.com/Articles/10324/Compiling-code-during-runtime

This example is good coz you can create dll file and so it can be shared between other applications.

Basically you can search for http://www.codeproject.com/search.aspx?q=csharpcodeprovider&x=0&y=0&sbo=kw&pgnum=6 and get more useful links.

Stalinist answered 10/4, 2014 at 18:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.