如何在winforms,.net中设计时获取应用程序路径?

时间:2010-01-24 02:13:21

标签: c# .net winforms path design-time

如果在引用的dll中使用Application.StartupPath,则该路径指向IDE的路径。

无论如何都要获得实际应用的路径?

为了清楚起见,这是在设计时。

ETA:我发布了以下解决方案:

ETA2:

因为它是相关的,我想我会发布另一个有用的设计时服务的片段。与下面的解决方案类似,此示例适用于UITypeEditor:

Public Overrides Function EditValue(ByVal context As System.ComponentModel.ITypeDescriptorContext, ByVal provider As System.IServiceProvider, ByVal value As Object) As Object

    Dim typeDiscovery As ITypeDiscoveryService = TryCast(provider.GetService(GetType(ITypeDiscoveryService)), ITypeDiscoveryService)
    Dim types As ICollection = typeDiscovery.GetTypes(GetType(MyType), False)

End Function

类型将包含从MyType派生的所有类型。将第二个参数更改为True以排除搜索GAC。 将Nothing作为获取所有类型列表的第一个参数。

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

以下是如何从UITypeEditor中执行此操作。

ETA:原始代码有一个额外不需要的步骤。我忘了我们有一个serviceprovider,所以不需要查看该网站。简化的代码是:

Public Class MyEditor
    Inherits UITypeEditor

    Public Overrides Function EditValue(ByVal context As System.ComponentModel.ITypeDescriptorContext, ByVal provider As System.IServiceProvider, ByVal value As Object) As Object

        Dim typeRes As ITypeResolutionService = TryCast(provider.GetService(GetType(ITypeResolutionService)), ITypeResolutionService)
        Dim ass As System.Reflection.AssemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName()
        MessageBox.Show(ass.CodeBase, "Design-time Path")
        MessageBox.Show(typeRes.GetPathOfAssembly(ass), "Run-time Path")

    End Function

End Class

原始代码:

Public Class MyEditor
    Inherits UITypeEditor

    Public Overrides Function EditValue(ByVal context As System.ComponentModel.ITypeDescriptorContext, ByVal provider As System.IServiceProvider, ByVal value As Object) As Object

        Dim component As IComponent = TryCast(context.Instance, IComponent)
        Dim site As ISite = component.Site
        Dim typeRes As ITypeResolutionService = TryCast(site.GetService(GetType(ITypeResolutionService)), ITypeResolutionService)
        Dim ass As System.Reflection.AssemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName()
        MessageBox.Show(ass.CodeBase, "Design-time Path")
        MessageBox.Show(typeRes.GetPathOfAssembly(ass), "Run-time Path")

    End Function

End Class

此解决方案基于How to: Access Design-Time Services的代码,您可以在其中找到大量信息。

答案 2 :(得分:-2)

你不能在设计时做到这一点!在运行时,您可以,也就是说,在构建应用程序并运行它,或在VS中点击F5或单击绿色箭头时。你为什么要在设计时知道?这是无关紧要的,因为可执行文件及其相关的DLL并没有真正加载到内存中并执行,而且,如果对代码进行了更改,则必须重新构建整个项目。

希望这有帮助, 最好的祝福, 汤姆。