Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Text

Namespace Reflection

    ''' <summary>
    ''' Provides helper methods for assembly reflection.
    ''' </summary>
    ''' <remarks></remarks>
    Public NotInheritable Class AssemblyHelper

        Private Shared Function GetModuleFileName(ByVal hModule As IntPtr, ByVal lpFilename() As Byte, ByVal nSize As Integer) As Integer
        End Function

        ''' <summary>
        ''' Gets the process executable in the default application domain. In other 
        ''' application domains, this is the first executable that was executed by 
        ''' AppDomain.ExecuteAssembly.
        ''' </summary>
        ''' <returns>The assembly that is the process executable in the default application 
        ''' domain, or the first executable that was executed by AppDomain.ExecuteAssembly.</returns>
        ''' <remarks></remarks>
        Public Shared Function GetEntryAssembly() As Assembly
            Dim arr = New Byte(256 * Marshal.SystemDefaultCharSize) {}
            Dim moduleFileName = AssemblyHelper.GetModuleFileName(IntPtr.Zero, arr, 255)
            If (moduleFileName <= 0) Then _
                Return Nothing
            If moduleFileName > 255 Then _
                Throw New System.IO.PathTooLongException("Assembly name is longer than MAX_PATH chararcters.")
            Dim str = Encoding.Unicode.GetString(arr, 0, moduleFileName * Marshal.SystemDefaultCharSize)
            Return Assembly.LoadFrom(str)
        End Function

    End Class

End Namespace