Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSharpCodeProvider doesn't return compiler warnings when there are no errors

I'm using the CSharpCodeProvider class to compile a C# script which I use as a DSL in my application. When there are warnings but no errors, the Errors property of the resulting CompilerResults instance contains no items. But when I introduce an error, the warnings suddenly get listed in the Errors property as well.

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 to I get hold of the warnings when there are no errors? By the way, I don't want to set TreatWarningsAsErrors to true.

like image 663
Sandor Drieënhuizen Avatar asked Jun 13 '10 13:06

Sandor Drieënhuizen


2 Answers

You didn't set CompilerParameters.WarningLevel

like image 114
abatishchev Avatar answered Nov 14 '22 23:11

abatishchev


It worked fine for me, after I fixed the other compile errors in your code (The comment characters) and set compilerParameters.WarningLevel.

like image 42
Jay Bazuzi Avatar answered Nov 15 '22 00:11

Jay Bazuzi