CSharpCodeProvider does not return compiler warnings when there are no errors

I am using the CSharpCodeProvider class to compile a C # script, which I use as DSL in my application. When there are warnings but no errors, the Errors property of the resulting instance of CompilerResults contains no elements. But when I entered the error, warnings suddenly fall into the Errors property.

 string script = @" using System; using System; // generate a warning namespace MyNamespace { public class MyClass { public void MyMethod() { // uncomment the next statement to generate an error //intx = 0; } } } "; CSharpCodeProvider provider = new CSharpCodeProvider( new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } }); CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = true; CompilerResults results = provider.CompileAssemblyFromSource( compilerParameters, script); foreach (CompilerError error in results.Errors) { Console.Write(error.IsWarning ? "Warning: " : "Error: "); Console.WriteLine(error.ErrorText); } 

So, how can I get warnings when there are no errors? By the way, I do not want to set TreatWarningsAsErrors to true .

+6
compiler-construction c # compilation
source share
2 answers

You have not set CompilerParameters.WarningLevel

+1
source share

This worked for me after I fixed other compilation errors in your code (comment characters) and set compilerParameters.WarningLevel .

+1
source share

All Articles