该System.Diagnostics.Process.Start()
方法接受ProcessStartInfo
用没有路径的可执行文件初始化的类实例,例如Notepad.exe
。该过程开始后,您可以找到其使用的完整路径,例如C:\Windows\SysWOW64\notepad.exe
。这是完美的,除非您想在不实际启动程序的情况下了解完整路径。就我而言,我想提前从可执行文件中获取图标。
这类似于Windows“ where”命令的行为,例如:
C:>where notepad.exe
C:>\Windows\System32\notepad.exe
C:>\Windows\notepad.exe
第一个响应C:\Windows\System32\notepad.exe
与“ Process”所使用的基本相同。
搜索路径的顺序实际上与注册表有关,因此不能保证仅通过PATH环境变量进行枚举即可产生预期的结果,尤其是在当前工作目录中存在具有预期名称的文件的情况下。为了可靠地获取可执行文件路径,您将需要SearchPath
在Kernel32中调用Win32函数。
没有公开的框架.NET函数SearchPath
,但是可以通过P / Invoke直接调用该函数。
下面的示例程序说明了此功能的用法。如果notepad.exe存在于系统搜索路径中,则按照系统配置,它将打印路径;否则,系统将显示路径。如果不存在,它将打印“找不到文件”。
using System;
using System.Text;
using System.Runtime.InteropServices;
class Program
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint SearchPath(string lpPath,
string lpFileName,
string lpExtension,
int nBufferLength,
[MarshalAs ( UnmanagedType.LPTStr )]
StringBuilder lpBuffer,
out IntPtr lpFilePart);
const int MAX_PATH = 260;
public static void Main()
{
StringBuilder sb = new StringBuilder(MAX_PATH);
IntPtr discard;
var nn = SearchPath(null, "notepad.exe", null, sb.Capacity, sb, out discard);
if (nn == 0)
{
var error = Marshal.GetLastWin32Error();
// ERROR_FILE_NOT_FOUND = 2
if (error == 2) Console.WriteLine("No file found.");
else
throw new System.ComponentModel.Win32Exception(error);
}
else
Console.WriteLine(sb.ToString());
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句