[英]C#: How to get the executable path that Process.Start will use when given a file with no path?
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環境變量進行枚舉即可產生預期的結果,尤其是在當前工作目錄中存在具有預期名稱的文件的情況下。 為了可靠地獲取可執行路徑,您將需要在Kernel32中調用SearchPath
Win32函數。
沒有公開SearchPath
框架.NET函數,但是可以通過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());
}
}
如果在命令行中輸入應用程序名稱(如notepad.exe),它將在當前目錄和PATH
環境變量中指定的所有路徑中搜索。 當您使用Process.Start
時,這類似地工作。 因此,您需要在PATH
環境變量的所有路徑中搜索可執行文件,然后從中提取圖標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.