0

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";
        }
aejs
  • 1
  • 2
    I assume this is an exercise/placeholder for what you're *really* trying to do, right -- which is what, exactly? In general processes have "no right" to look at the innards of other processes; in particular, there is no API that will tell you which file Notepad has open for editing purposes (or even that Notepad does such things at all). The best you can do is use internal APIs to get a list of *all* files Notepad has open for whatever purpose, which will include the file being edited, but will also include things like DLL files. Specific processes would require specific approaches. – Jeroen Mostert May 25 '22 at 10:54
  • 1
    https://stackoverflow.com/questions/177146/how-do-i-get-the-list-of-open-file-handles-by-process-in-c – Dmitry Bychenko May 25 '22 at 11:34

0 Answers0