trying to compile and execute C# code programmatically

前端 未结 3 447
悲&欢浪女
悲&欢浪女 2021-01-14 20:46

The following is my code :

using System;
using System.Collections.Generic;
using System.Text;

using System.CodeDom.Compiler;
using System.IO;
using Microsof         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-14 21:35

    I believe this is the problem:

    string content = File.ReadAllText(@"D:\hi.cs");
    string[] code = new string[content.Length];
    char[] seperators = { '\n','\r','\t' };
    code = content.Split(seperators);
    

    The idea (I believe) is that CompileAssemblyFromSource doesn't take individual lines - each string in the array is meant to be a complete C# source file. So you probably just need:

    string[] code = new[] { File.ReadAllText(@"D:\hi.cs") };
    

    Note that even if your first block were doing the right thing, you'd still have been creating a string array for no reason - it would have been simpler to write it as:

    string content = File.ReadAllText(@"D:\hi.cs");
    char[] seperators = { '\n','\r','\t' };
    string[] code = content.Split(seperators);
    

提交回复
热议问题