Click here to Skip to main content
15,896,207 members

Finding character index of method in C# source file.

jmh1 asked:

Open original thread
I am using C# as a scripting language i my app with CS-Script as the compiler interface. When a script causes a runtime error, the exception stacktrace contains information on the namespace, class and methodname of the method causing the exception.

I have the source code in a string which contains many methods in different namespaces and classes.

Detecting a runtime error, i have parsed out namespace, class and method name where the error occured. Now i need to find the character index in the source string where the failing method is declared. Having that index, i can find the line number and can then tell the user where the error occurred.

Lets say the code looks like this:
C#
// Other code blocks with same or other namespace and same or other class names might
// precede the code.
// The Regex should not find MyMethod if it is not within MyNamespace and MyClass. 
 
namespace MyNamespace {
    public static class MyClass {

        public static int OtherMethod(int val) {
            return val * 2;
        }

        public static int MyMethod(int val) {
            return 10 / val;
        }

    }
}


What is known is that the namespace is MyNamespace, that the class is MyClass and that the method name we are looking for is MyMethod.

What i need to find out is that the identifier MyMethod within this namespace and class is declared at line y in the code.

I have tried to make a C# Regex expression, but i can't make it work and now these Regex hieroglyphs are beginning to give me a bad headache. What i came up with is this:

".*namespace\s+MyNamespace.*class\s+MyClass.*MyMethod\s*\("

How do I do this?
Tags: C#, Regular Expressions

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900