Find C# Source Code
Finds the C# source code of a top-level member (Method, Property, Class, etc.) by name, including nested classes and partial methods.
VB
Public Function FindCSharpSourceCode(assemblyPath As String,
memberName As String) As String
Try
' Step 1: locate solution root
Dim dir As DirectoryInfo = Directory.GetParent(assemblyPath)
While dir IsNot Nothing AndAlso Not dir.GetFiles("*.sln").Any()
dir = dir.Parent
End While
If dir Is Nothing Then Return ""
' Step 2: scan all .cs files
Dim csFiles = Directory.GetFiles(dir.FullName, "*.cs", SearchOption.AllDirectories)
For Each csFile In csFiles
Dim lines = File.ReadAllLines(csFile)
For i = 0 To lines.Length - 1
Dim line = lines(i).Trim()
' Check for a potential declaration containing the member name
If line.Contains(memberName) Then
' Possible property (with { get; set; }), method, constructor, class, etc.
If line.Contains("{") OrElse (i + 1 < lines.Length AndAlso lines(i + 1).Trim().StartsWith("{")) Then
Dim buffer As New List(Of String)
Dim braceCount As Integer = 0
' Check backward in case of attributes or partial keywords
Dim startIdx = i
While startIdx > 0 AndAlso (lines(startIdx - 1).Trim().StartsWith("[") OrElse
lines(startIdx - 1).Trim().StartsWith("partial") OrElse
String.IsNullOrWhiteSpace(lines(startIdx - 1)))
startIdx -= 1
End While
' Start collecting from startIdx
For j = startIdx To lines.Length - 1
Dim currentLine = lines(j)
buffer.Add(currentLine)
braceCount += currentLine.Count(Function(c) c = "{"c)
braceCount -= currentLine.Count(Function(c) c = "}"c)
If braceCount = 0 AndAlso buffer.Count > 1 Then
Exit For
End If
Next
' Validate that it is indeed the correct member block
Dim codeBlock = String.Join(vbCrLf, buffer)
If codeBlock.Contains(memberName) Then
Return codeBlock
End If
End If
End If
Next
Next
Return ""
Catch ex As Exception
Return ""
End Try
End Function