2012-04-16 61 views
0

是否可以在文本框中編譯任何給定的C#代碼,然後將其保存到exe中?在文本框中編譯代碼並保存爲exe

這可能嗎?如果是這樣,該怎麼辦?

+2

您是否自己對此主題進行過任何研究?如果是這樣,你發現了什麼? – 2012-04-16 16:18:44

+0

是的,我發現只是運行時編譯,但沒有保存。 – 2012-04-16 16:19:30

+0

你有沒有在這裏看看http://www.codeproject.com/Articles/9019/Compiling-and-Executing-Code-at-Runtime – 2012-04-16 16:20:58

回答

4

是的,這是可能的。您可以使用CodeDOM。而這裏的an example

using System; 
using System.Collections.Generic; 
using System.Linq; 
using Microsoft.CSharp; 
using System.CodeDom.Compiler; 
class Program 
{ 
    static void Main(string[] args) 
    { 
     var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } }); 
     var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true); 
     parameters.GenerateExecutable = true; 
     CompilerResults results = csc.CompileAssemblyFromSource(parameters, 
     @"using System.Linq; 
      class Program { 
       public static void Main(string[] args) { 
       var q = from i in Enumerable.Rnge(1,100) 
          where i % 2 == 0 
          select i; 
       } 
      }"); 
     results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText)); 
    } 
} 
+0

謝謝,真的很有幫助。 – 2012-04-16 16:27:36

0

除了在運行時編譯的代碼,你可以從你的文本保存到磁盤的代碼,然後用csc.exe編譯它。該命令看起來類似於以下內容:

%systemroot%\Microsoft.NET\Framework\v3.5\csc /out:filename.exe filename.cs