How to get a process working dir on Windows?
c++, winapi, windows
Solution
You need heavier artillery than PSAPI for this. Here's how to do it (x86 assumed, error handling omitted):
ProcessBasicInformation pbi ;
RTL_USER_PROCESS_PARAMETERS upp ;
PEB peb ;
DWORD len ;
HANDLE handle = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid) ;
NtQueryInformationProcess (handle, 0 /*ProcessBasicInformation*/, &pbi,
sizeof (ProcessBasicInformation), &len) ;
ReadProcessMemory (handle, pbi.PebBaseAddress, &peb, sizeof (PEB), &len) ;
ReadProcessMemory (handle, peb.ProcessParameters, &upp, sizeof (RTL_USER_PROCESS_PARAMETERS), &len) ;
WCHAR path = new WCHAR[upp.CurrentDirectoryPath.Length / 2 + 1] ;
ReadProcessMemory (handle, upp.CurrentDirectoryPath.Buffer, path, upp.CurrentDirectoryPath.Length, &len) ;
// null-terminate
path[upp.CurrentDirectoryPath.Length / 2] = 0 ;
Note that this approach contains a race unless the process is suspended.
Problem
How to get a process working dir on Windows using native API (for another process using process handle or PID)? I've watched Process and Thread Functions, PSAPI Functions and haven't found. Maybe WMI? Also, regarding these topics, how PSAPI relates to Process and Thread Functions? Is it outdated?