如何在控制台应用程序中找到应用程序的路径?
在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。
如何在控制台应用程序中找到应用程序的路径?
在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。
当前回答
你可以简单地添加到你的项目引用System.Windows.Forms,然后像往常一样使用System.Windows.Forms. application . startuppath。
因此,不需要更复杂的方法或使用反射。
其他回答
我使用这个如果exe被认为是通过双击它来调用
var thisPath = System.IO.Directory.GetCurrentDirectory();
这里有一个可靠的解决方案,适用于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等,也有限制控制,如杀死等*
在。net6中,我的WPF应用程序(<TargetFramework>net6.0-windows</TargetFramework>)返回Assembly.GetEntryAssembly()的.dll文件路径!位置,而不是。exe文件。他们引入了System.Environment.ProcessPath:
var path = Environment.ProcessPath; // Note it may be null
返回启动当前执行进程的可执行文件的路径。当路径不可用时返回null。
请参见这里和这里的讨论。
你可以用这个代替。
System.Environment.CurrentDirectory
可以使用“解决方案资源管理器”在项目中创建文件夹名称为“资源”,然后可以在“资源”中粘贴文件。
private void Form1_Load(object sender, EventArgs e) {
string appName = Environment.CurrentDirectory;
int l = appName.Length;
int h = appName.LastIndexOf("bin");
string ll = appName.Remove(h);
string g = ll + "Resources\\sample.txt";
System.Diagnostics.Process.Start(g);
}