如何在控制台应用程序中找到应用程序的路径?

在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。


当前回答

这里有一个可靠的解决方案,适用于32位和64位应用程序。

添加以下参考:

使用System.Diagnostics; 使用System.Management;

将此方法添加到项目中:

public static string GetProcessPath(int processId)
{
    string MethodResult = "";
    try
    {
        string Query = "SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;

        using (ManagementObjectSearcher mos = new ManagementObjectSearcher(Query))
        {
            using (ManagementObjectCollection moc = mos.Get())
            {
                string ExecutablePath = (from mo in moc.Cast<ManagementObject>() select mo["ExecutablePath"]).First().ToString();

                MethodResult = ExecutablePath;

            }

        }

    }
    catch //(Exception ex)
    {
        //ex.HandleException();
    }
    return MethodResult;
}

现在像这样使用它:

int RootProcessId = Process.GetCurrentProcess().Id;

GetProcessPath(RootProcessId);

注意,如果您知道进程的id,那么该方法将返回相应的ExecutePath。

有兴趣的同学可以额外订阅:

Process.GetProcesses() 

...将为您提供当前运行的所有进程的数组,并且…

Process.GetCurrentProcess()

...会给你当前的进程,以及他们的信息,如Id等,也有限制控制,如杀死等*

其他回答

下面一行将给出应用程序路径:

var applicationPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)

上述解决方案在以下情况下正常工作:

简单的应用 在另一个域,Assembly.GetEntryAssembly()将返回null DLL以字节数组的形式从嵌入式资源加载,并以Assembly.Load的形式加载到AppDomain。 使用Mono的mkbundle bundles(没有其他方法工作)

对于任何对asp.net web应用程序感兴趣的人。以下是我用3种不同方法得出的结果

protected void Application_Start(object sender, EventArgs e)
{
  string p1 = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
  string p2 = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
  string p3 = this.Server.MapPath("");
  Console.WriteLine("p1 = " + p1);
  Console.WriteLine("p2 = " + p2);
  Console.WriteLine("p3 = " + p3);
}

结果

p1 = C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\a897dd66\ec73ff95\assembly\dl3\ff65202d\29daade3_5e84cc01
p2 = C:\inetpub\SBSPortal_staging\
p3 = C:\inetpub\SBSPortal_staging

应用程序在物理上从“C:\inetpub\SBSPortal_staging”运行,所以第一个解决方案绝对不适合web应用程序。

Assembly.GetEntryAssembly()。Location或Assembly.GetExecutingAssembly().Location

与System.IO.Path.GetDirectoryName()结合使用只获取目录。

来自GetEntryAssembly()和GetExecutingAssembly()的路径可以不同,即使在大多数情况下目录是相同的。

使用GetEntryAssembly(),你必须意识到,如果入口模块是非托管的(即c++或VB6可执行文件),它可能返回null。在这些情况下,可以使用Win32 API中的GetModuleFileName:

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);

你可以简单地添加到你的项目引用System.Windows.Forms,然后像往常一样使用System.Windows.Forms. application . startuppath。

因此,不需要更复杂的方法或使用反射。

您可以使用下面的代码来获取当前应用程序目录。

AppDomain.CurrentDomain.BaseDirectory