I can't figure out how to get the absolute path of a file from the process. For example, I am searching for the absolute file path of a .txt file which is opened in notepad.
So far I get the process ID of the foreground window. Use that to create an instance of a Process class by using GetProcessById().
I tried the FileName of the main module of the process, however that gives me the location of the executable, not the file itself!
public static int GetActiveWindowPid()
{
int processID = 0;
uint threadID = GetWindowThreadProcessId(GetForegroundWindow(), out processID);
return processID;
}
public static Process CreateProcess()
{
Process process = Process.GetProcessById(GetActiveWindowPid());
return process;
}
public static string GetFilePath(Process process)
{
//return the filepath of the main module of the process
//return process.MainModule.FileName;
try
{
return process.MainModule.FileName;
}
catch
{
string query = "SELECT ExecutablePath, ProcessID FROM Win32_Process";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject item in searcher.Get())
{
object id = item["ProcessID"];
object path = item["ExecutablePath"];
if (path != null && id.ToString() == process.Id.ToString())
{
return path.ToString();
}
}
}
return "Error";
}