Re: Live parsing of C# code.
Quote:
Originally Posted by dahwan
So to sum up:
I need to make a program that is able to run C# code directly from an uncompiled cs file.
Is this possible?
You mean to ask, you have a code kept in .cs file that you want to compile it from your application and make an exe. ?
If what i assumed is correct, then it can be done.
Have a look
http://code-in-action.blogspot.com/2...om-c-code.html
Hope it helps !!
MMH
Re: Live parsing of C# code.
I think what our pal wants is actually to avoid having to compile in a separate executable file.
I am no expert, but I think you need to generate an assembly from your .cs file in order to execute it, the sample on the link MMH provided builds a .exe, but it could surely be adapted to genrate a dll instead.
Once your dll is compiled, it would be easy for you to load it and retrieve the class and methods you would want to access, and execute them.
Code:
public static Type LoadFromFile(string fileName, string className)
{
//Load assembly from file
Assembly myAssembly = Assembly.LoadFrom(fileName);
// Get the Type object for this class
Type ClassType = myAssembly.GetType(className);
//return the type
return ClassType;
}
Re: Live parsing of C# code.
1. Yes, it is possible.
2. C# is not scripting language, look at DLR.
3. Check this thread.
Re: Live parsing of C# code.
I want to do the equal of the javascript function that takes a string and executes it as javascript code. But i want it in C#
Re: Live parsing of C# code.
The Mono project just released some early stuff for a C# REPL (ie, a C# Shell) - which basically requires an Eval() method for C#...
In other words - http://tirania.org/blog/archive/2008/Sep-10.html
Re: Live parsing of C# code.
You can do this, but you will run into problems when the "external" compiled method needs to access data from your parent application.
You can tell the compiler to generate a dll in memory that you can then invoke methods from.
Rough example:
Code:
CodeDomProvider provider = null;
CompilerResults cr = null;
provider = new Microsoft.CSharp.CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
//Add referenced assemblies
cp.ReferencedAssemblies.Add("system.dll");
cp.ReferencedAssemblies.Add("system.windows.forms.dll");
// Compile in memory
cp.GenerateInMemory = true;
//Compile the code
cr = provider.CompileAssemblyFromSource(cp, sourceCodeFile);
//Load the new assembly - object
Assembly loAssembly = cr.CompiledAssembly;
object loObject = loAssembly.CreateInstance("SomeObject");
//Call method
object loResult = loObject.GetType().InvokeMember("SomeMethod",BindingFlags.InvokeMethod,null,loObject,loCodeParms);
I pulled this code from a project where I attempted to do the same thing you are suggesting (scripting a game).
It wasn't long before I realized this was the wrong way to go about this.
Your mileage may vary.
-C6