获取 Windows Forms 应用程序的执行目录路径

61

我想获取Windows Forms应用程序执行目录的路径。(即可执行文件所在的目录。)

有没有人知道.NET中是否存在内置方法可以实现这一点?


这个回答解决了你的问题吗?获取应用程序文件夹路径的最佳方法 - Michael Freidgeim
8个回答

69
在VB.NET中
Dim directory as String = My.Application.Info.DirectoryPath

在C#中

string directory = AppDomain.CurrentDomain.BaseDirectory;

4
C#中的这个位置也适用于VB或其他不支持"My"命名空间的语言。 - Joel Coehoorn
@Tomas Pajonk,我可以建议将C#中的“FileName”变量更改为“directory”吗? - grenade

60

Application.Current会得到当前应用程序域的结果。 http://msdn.microsoft.com/en-us/library/system.appdomain_members.aspx

此外,这也可以提供程序集的位置。

AppDomain.CurrentDomain.BaseDirectory

我记得有多种方法可以获取应用程序的位置,但至少这种方法在以前对我有效过(自从我做winforms编程以来已经有一段时间了 :/)。


2
应该是 Application.CurrentDomain。 - Max
1
这似乎在.NET 4.0中无法工作,但Application.UserAppDataPath可以工作。 - criticalfix
1
AppDomain.CurrentDomain.BaseDirectory - A Khudairy

19

这可能有所帮助;

Path.GetDirectoryName(Application.ExecutablePath);

这里还有一个参考链接


9
我认为 System.Windows.Forms.Application.StartupPath 可以解决你的问题。

2

这两个示例都是使用VB.NET编写的。

调试路径:

TextBox1.Text = My.Application.Info.DirectoryPath

可执行文件路径:

TextBox2.Text = IO.Path.GetFullPath(Application.ExecutablePath)

1

看这个:

Imports System.IO
Imports System.Management

Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox1.Text = Path.GetFullPath(Application.ExecutablePath)
        Process.Start(TextBox1.Text)
    End Sub
End Class

1
string apppath = 
    (new System.IO.FileInfo
    (System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).DirectoryName;

抱歉,汇编命名空间和代码显示面板不兼容。我讨厌滚动条。 - MusiGenesis

0
Private Sub Main_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    Dim args() As String = Environment.GetCommandLineArgs()
    If args.Length > 0 Then
        TextBox1.Text = Path.GetFullPath(Application.ExecutablePath)
        Process.Start(TextBox1.Text)   
    End If
End Sub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接