2

Possible Duplicate:
C# eval equivalent?

Hi - I was wondering how I can execute a user provided string containing c# code from my application.

Example:

string userProvidedString = "Console.Write("Hello World!")";

ExecuteCode(userProvidedString); // Should output Hello World!
Community
  • 1
  • 1
ace
  • 2,141
  • 7
  • 29
  • 39
  • I know i need to sanitize code before executing, also the code will actually not come from the end user but from a client application i will have total control over. In the question i'm just over simplifying the problem. – ace Feb 16 '11 at 23:46
  • 1
    Executing arbitrary user provided code can be very dangerous if not sanitized properly. Also, C#, being a compiled language is not the best venue for this sort of thing. If there is a small subset of code that you want to evaluate and execute you can usually write your own mini interpreter that just understands and does exactly what you need. Executing arbitrary code is another matter -- dynamic languages have 'eval()' statements that allow you to do this, but not C# natively. – Jesse Cohen Feb 16 '11 at 23:53
  • The only reason I can think of to do this in practice would be to develop a programming or debugging tool of some kind. In that sense it's no more dangerous than using visual studio. – Jamie Treworgy Feb 16 '11 at 23:53

2 Answers2

4

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

Mike Cole
  • 14,474
  • 28
  • 114
  • 194
4

There's a CSharpCodeProvider Class in Framework that can be utilized. It contains a CompileAssemblyFromSource method that Parses and compiles the code in a String.

You might also like checking this blog post on MSDN: http://blogs.msdn.com/b/dohollan/archive/2010/08/09/programmatically-invoke-the-c-compiler.aspx

NOTE: The above blog post link does not work anymore, so use this one instead: https://learn.microsoft.com/en-us/archive/blogs/dohollan/programmatically-invoke-the-c-compiler

J03L
  • 314
  • 3
  • 17
Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79