我最近安裝了Visual Studio 11測試版,並試圖更新現有的4.0項目以使用4.5。在程序中,它使用CSharpCodeProvider
編譯一些動態生成的代碼。使用CSharpCodeProvider與.net 4.5測試版
/// <summary>
/// Compile and return a reference to the compiled assembly
/// </summary>
private Assembly Compile()
{
var referencedDlls = new List<string>
{
"mscorlib.dll",
"System.dll",
"System.Core.dll",
};
referencedDlls.AddRange(RequiredReferences);
var parameters = new CompilerParameters(
assemblyNames: referencedDlls.ToArray(),
outputName: GeneratedDllFileName,
// only include debug information if we are currently debugging
includeDebugInformation: Debugger.IsAttached);
parameters.TreatWarningsAsErrors = false;
parameters.WarningLevel = 0;
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = false;
parameters.CompilerOptions = "/optimize+ /platform:x64";
string[] files = Directory.GetFiles(GenerationDirectory, "*.cs");
var compiler = new CSharpCodeProvider(
new Dictionary<string, string> { { "CompilerVersion", "v4.5" } });
var results = compiler.CompileAssemblyFromFile(parameters, files);
if (results.Errors.HasErrors)
{
string firstError =
string.Format("Compile error: {0}", results.Errors[0].ToString());
throw new ApplicationException(firstError);
}
else
{
return results.CompiledAssembly;
}
}
問題是當我改變了CompilerVersion
從{ "CompilerVersion", "v4.0" }
到{ "CompilerVersion", "v4.5" }
我現在得到一個異常
編譯器可執行文件CSC.EXE無法找到。
是否指定CompilerVersion
錯誤的方式告訴它使用4.5?將它編譯爲v4.5甚至會有所作爲,因爲代碼不會使用任何新的4.5特定功能?
我不知道這是錯誤的指定編譯器的版本一樣,但FWIW在.NET 4.5編譯器仍然是根據輸出4.0版本。 – 2012-03-06 20:48:39
爲什麼你只返回第一個錯誤? – abatishchev 2012-03-07 17:28:48
@abatishchev由於我正在編譯的代碼都是自動生成的,因此通常不應該有任何錯誤,除非模板混亂了,只是返回第一個阻止它返回可能的數千個錯誤,這隻會導致一個非常長的錯誤電子郵件,而不是真的有幫助 – BrandonAGr 2012-03-07 17:45:10