running external C# file in a program

2019-06-24 04:31发布

问题:

Does the .NET framework have any classes which allow you to run (compile, interpret or whatever) an external script file containing C# code?

For instance, if I have a file Hello.cs containing this:

class Hello
//This program displays Hello World
{
    static public void Main()
    {
        System.Console.WriteLine("Hello World");
    }
}

how can i load the code above, from within a winform, app and execute it?

I'm interested in the load/execute logic; the program could be anything, from a console app to another winform app.

Does Reflection allow this?

回答1:

Check out the following article: C#: Writing extendable applications using on-the-fly compilation.



回答2:

Does the .NET framework have any classes which allow you to run (compile, interpret or whatever) an external script file containing C# code?

Yes, you can use the CodeDomProvider class.

how can i load the code above, from within a winform, app and execute it?

Well,after compile the C# code using the above class,you can use the ProcessStartInfo class and pass it as argument of Start method from Process class and then read the StandardOutput stream,store it on a string and show as you want,Console.Write(), MessageBox.Show() etc.



回答3:

I would check the Roslyn APIs. You can do what ever you want as long as you provide valid C# o VB.NET code.