My.Application.Info.DirectoryPath和Application.StartupPath之间有什么区别

时间:2015-02-18 16:46:29

标签: vb.net

这个问题确实说明了。有什么不同?我想要获得应用程序安装的路径,到目前为止两者之间没有差异。

我在MSDN页面中看到的唯一区别是Application.StartupPath提到ClickOnce应用程序(我没有运行ClickOnce应用程序 - 无法忍受它们!)

通过Intellisense查看可能还有其他方法可以实现。这只是一个不仅仅是一种皮肤猫的方式吗?或者每种方法都有优点和缺点吗?

1 个答案:

答案 0 :(得分:2)

My命名空间中包含的类型包含在Microsoft.VisualBasic.dll中 - 它们通常(或永远!)在其他.NET语言中使用。 Application命名空间内的那些是。

在幕后,Application.StartupPath执行此操作:

Public ReadOnly Shared Property StartupPath As String
    Get
        If (Application.startupPath Is Nothing) Then
            Dim stringBuilder As System.Text.StringBuilder = New System.Text.StringBuilder(260)
            UnsafeNativeMethods.GetModuleFileName(NativeMethods.NullHandleRef, stringBuilder, stringBuilder.Capacity)
            Application.startupPath = Path.GetDirectoryName(stringBuilder.ToString())
        End If
        (New FileIOPermission(FileIOPermissionAccess.PathDiscovery, Application.startupPath)).Demand()
        Return Application.startupPath
    End Get
End Property

虽然My.Application.Info.DirectoryPath执行此操作:

Public ReadOnly Property DirectoryPath As String
    Get
        Return Path.GetDirectoryName(Me.m_Assembly.Location)
    End Get
End Property

称之为:

Public Overrides ReadOnly Property Location As String
    <SecuritySafeCritical>
    Get
        Dim str As String = Nothing
        RuntimeAssembly.GetLocation(Me.GetNativeHandle(), JitHelpers.GetStringHandleOnStack(str))
         If (str IsNot Nothing) Then
            (New FileIOPermission(FileIOPermissionAccess.PathDiscovery, str)).Demand()
        End If
        Return str
    End Get
End Property
GetModuleFileName中使用的{p> StartupPath是对native Win32 API的调用,GetLocation中使用的DirectoryPath涉及"native" call to the .NET CLR Runtime,所以你&# 39; d需要深入挖掘以找出它从何处获取信息。

<强> TL; DR

使用Application.StartupPath作为偏好并帮助养成良好的习惯,因为它不依赖于Microsoft.VisualBasic对.NET的补充,并且如果您将更容易过渡到其他语言永远选择使用它们。

相关问题