2009-01-26 31 views
4

我正在爲我的大學課程之一開發簡單的C#編輯器,並且需要向編譯器發送一個.cs文件並收集錯誤(如果存在)並在我的應用程序中顯示它們。換句話說,我想將C#編譯器添加到我的編輯器中。調試器有沒有這樣的事情?訪問編譯器的錯誤和警告

回答

8

如果使用CodeDomProvider

using System.CodeDom; 
using System.CodeDom.Compiler; 
using Microsoft.CSharp; 

// the compilation part 

// change the parameters as you see fit 
CompilerParameters cp = CreateCompilerParameters(); 
var options = new System.Collections.Generic.Dictionary<string, string>(); 
if (/* you want to use the 3.5 compiler*/) 
{ 
    options.Add("CompilerVersion", "v3.5"); 
} 
var compiler = new CSharpCodeProvider(options); 
CompilerResults cr = compiler.CompileAssemblyFromFile(cp,filename); 
if (cr.Errors.HasErrors) 
{ 
    foreach (CompilerError err in cr.Errors) 
    { 
     // do something with the error/warning 
    } 
} 
1

使用System.Diagnostics.Process類啓動通用過程並從標準輸入/輸出收集I/O。

對於這個特定場景,我建議你看看Microsoft.CSharp.CSharpCodeProvider類。它會爲你完成任務。