running external C# file in a program

2019-06-24 04:41发布

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?

3条回答
Juvenile、少年°
2楼-- · 2019-06-24 05:16

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

查看更多
放我归山
3楼-- · 2019-06-24 05:23
乱世女痞
4楼-- · 2019-06-24 05:23

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.

查看更多
登录 后发表回答