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

2

6

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.

Fucoid answered 13/6, 2010 at 13:35 Comment(2)
btw, see #2611386 about GenerateInMemoryIndisputable
@Indisputable thanks, that's an interesting fact.Exception
I
1

You didn't set CompilerParameters.WarningLevel

Indisputable answered 13/6, 2010 at 13:42 Comment(3)
I tried that already but it didn't make any difference. Besides, the warnings do get reported if there is at least an error. That wouldn't happen if the warning level was set to an inappropriate level.Exception
So it turns out you were right after all, I had to set the warning level to 3 (I guess I only tried 0, 1 and perhaps 2). Because you were the first to suggest this, I accepted your answer.Exception
@Sandor: Thank you! As far as I could understand from Reflector WarningLevel is being set by default to 4. But in MSDN nothing is said about that,Indisputable
S
1

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

Selfhood answered 13/6, 2010 at 23:47 Comment(1)
Thanks, setting it to 3 in this case appears to do the trick. I think is peculiar though that in case of one or more errors the warnings show up regardless of the warning level parameter value.Exception

© 2022 - 2024 — McMap. All rights reserved.