I was wondering if it was possible to compile, and run stored code, without generating an exe or any type of other files, basically run the file from memory.
Basically, the Main application, will have some stored code (code that will potentially be changed), and it will need to compile the code, and execute it. without creating any files.
creating the files, running the program, and then deleting the files is not an option. the compiled code will need to be ran from memory.
code examples, or pointers, or pretty much anything is welcome :)
Yeah, the nice thing with CodeDOM is that it can generate the assembly for you in memory (as well as providing error messages and other info in an easily readable format). @Noldorin, The C# CodeDOM implementation doesn't actually generate an assembly in memory.
CodeDom. Compiler namespace provides interfaces for generating source code from CodeDOM object graphs and for managing compilation with supported compilers. A code provider can produce source code in a particular programming language according to a CodeDOM graph.
After a developer writes the C# code, he or she compiles their code. This results in Common Intermediate Language stored within Portable Executable (PE for 32-bit, PE+ for 64-bit) files such as “.exe” and “. dll” files for Windows. These files are distributed to users.
To compile and execute a program in C#, you just need to click the Run button or press F5 key to execute the project in Microsoft Visual Studio IDE. Open a text editor and add the above-mentioned code. Open the command prompt tool and go to the directory where you saved the file. Type csc helloworld.
using (Microsoft.CSharp.CSharpCodeProvider foo = new Microsoft.CSharp.CSharpCodeProvider()) { var res = foo.CompileAssemblyFromSource( new System.CodeDom.Compiler.CompilerParameters() { GenerateInMemory = true }, "public class FooClass { public string Execute() { return \"output!\";}}" ); var type = res.CompiledAssembly.GetType("FooClass"); var obj = Activator.CreateInstance(type); var output = type.GetMethod("Execute").Invoke(obj, new object[] { }); }
This compiles a simple class from the source code string included, then instantiates the class and reflectively invokes a function on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With