如何在控制台应用程序中找到应用程序的路径?
在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。
如何在控制台应用程序中找到应用程序的路径?
在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。
当前回答
在。net Core 3及以上版本中,你会得到。dll文件而不是。exe文件。获取您可以使用的.exe文件路径。
var appExePath = Process.GetCurrentProcess().MainModule.FileName;
其他回答
在VB.net
My.Application.Info.DirectoryPath
工作为我(应用类型:类库)。不太懂c#… 返回文件名为字符串的路径
你可能会这样做:
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
这里有一个可靠的解决方案,适用于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等,也有限制控制,如杀死等*
.Location1 System.Reflection.Assembly.GetExecutingAssembly ()
如果你想要的只是目录,将它与System.IO.Path.GetDirectoryName结合起来。
根据minor先生的评论: System.Reflection.Assembly.GetExecutingAssembly()。Location返回正在执行的程序集当前所在的位置,该位置可能是也可能不是程序集未执行时所在的位置。在阴影复制程序集的情况下,您将获得临时目录中的路径。System.Reflection.Assembly.GetExecutingAssembly()。CodeBase将返回程序集的“永久”路径。
AppDomain.CurrentDomain.BaseDirectory
将解决问题,以引用第三方参考文件与安装包。