Re: Urgent pls -script engine

"Sean Greer (SBI-Chico)" <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.general
Message-ID <[email protected]>
Here is something I was playing with that will compile code contained in a
file into an in-memory assembly:

        public class AssemblyGenerator
        {
                public Assembly GenerateInMemoryAssembly(string codeFile)
                {
                        ICodeCompiler icc = (new
CSharpCodeProvider()).CreateCompiler();
                        CompilerParameters cp = new CompilerParameters();
                        cp.ReferencedAssemblies.Add("system.dll");
                        cp.ReferencedAssemblies.Add("codegenbase.dll");
                        cp.GenerateInMemory = true;

                        StreamReader reader = new StreamReader(codeFile);
                        string source = reader.ReadToEnd();
                        reader.Close();

                        CompilerResults cr =
icc.CompileAssemblyFromSource(cp, source);
                        return cr.CompiledAssembly;
                }
        }

        public class App
        {
                public static void Main()
                {
                        AssemblyGenerator ag = new AssemblyGenerator();
                        Assembly assem =
ag.GenerateInMemoryAssembly("test.cs");
                        CodeGenBase cgb = (CodeGenBase)
assem.CreateInstance("Test.TestObj");
                        cgb.SayHello();
                }
        }

The base class that TestObj derives from looks like this:

        public class CodeGenBase
        {
                public virtual void SayHello()
                {
                        Console.WriteLine("Hello from {0}",
this.ToString());
                }
        }

Hope that helps...

Seang

You can read messages from the DOTNET archive, unsubscribe from DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.