Question

For example, the code below can complile ok, but throw an exception at runtime. My question is, how to get the runtime error line number ? Thanks.

using System;
using System.Collections.Generic;
using System.Text;

namespace mytempNamespace {
    public class mytempClass : {

        public void show() {

            String msg=null;
            String msgNew=msg.Substring(3);
        }

    }

}

When i compile , the result is ok

CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
CompilerResults compilerResults = compiler.CompileAssemblyFromSource(parms, myClassCode);
Assembly assembly = compilerResults.CompiledAssembly;

When i invokde the method "show", the assembly throw an exception. How can i get runtime error line number in CodeDom?

No correct solution

OTHER TIPS

Use StackTrace to extract an exception's file, line, and column information.

StackTrace stackTrace = new StackTrace(exception, true);
if (stackTrace.FrameCount > 0)
{
    StackFrame frame = stackTrace.GetFrame(0);
    int lineNumber = frame.GetFileLineNumber();
    int columnNumber = frame.GetFileColumnNumber();
    string fileName = frame.GetFileName();
    string methodName = frame.GetMethod().Name;
    // do stuff
}

You'll need to compile your code with CompilerParameters set up to output debugging information:

CompilerParameters parms = new CompilerParameters()
{
    GenerateInMemory = false,
    IncludeDebugInformation = true,
    OutputAssembly = myOutputAssembly,
    // other params
};
CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
CompilerResults compilerResults = compiler.CompileAssemblyFromSource(parms, myClassCode);
Assembly assembly = compilerResults.CompiledAssembly;

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top