Find VB Source Code
Finds the VB.NET source code of a top-level member (Function, Sub, Property, Class, etc.) by name.
VB
Public Function FindVbSourceCode(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 .vb files
Dim vbFiles = Directory.GetFiles(dir.FullName, "*.vb", SearchOption.AllDirectories)
' Step 3: look for member declaration by type
Dim memberTypes = New Dictionary(Of String, String) From {
{"Function", "End Function"},
{"Sub", "End Sub"},
{"Property", "End Property"},
{"Class", "End Class"},
{"Module", "End Module"},
{"Interface", "End Interface"},
{"Structure", "End Structure"},
{"Enum", "End Enum"}
}
For Each vbFile In vbFiles
Dim lines = File.ReadAllLines(vbFile)
For Each kvp In memberTypes
Dim declType = kvp.Key
Dim endType = kvp.Value
Dim collecting As Boolean = False
Dim buffer As New List(Of String)
For Each line In lines
Dim trimmed = line.Trim()
If Not collecting AndAlso (trimmed.StartsWith("Public " & declType & " " & memberName) OrElse
trimmed.StartsWith("Private " & declType & " " & memberName) OrElse
trimmed.StartsWith("Friend " & declType & " " & memberName) OrElse
trimmed.StartsWith("Protected " & declType & " " & memberName) OrElse
trimmed.StartsWith(declType & " " & memberName)) Then
collecting = True
End If
If collecting Then
buffer.Add(line)
If trimmed.ToLower() = endType.ToLower() Then
Return String.Join(vbCrLf, buffer)
End If
End If
Next
Next
Next
Return ""
Catch
Return ""
End Try
End Function