-1

I create an application that records the user's activity history on the computer. At the moment I need to find out the path to the file (for example с:\documents\FileName.docx) that is open in the Word for example. I just got to know the path to the EXE file. I have process id, but in ManagementObject I did not find any information about executable file path. How can I do this? Below method how I take .exe file path by process id.

public static string GetMainModuleFilepath(int processId)
        {
            string wmiQueryString = "SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;
            using (var searcher = new ManagementObjectSearcher(wmiQueryString))
            {
                using (var results = searcher.Get())
                {
                    ManagementObject mo = results.Cast<ManagementObject>().FirstOrDefault();
                    return (string)mo?["ExecutablePath"];
                }
            }            
        }
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

I have tried a lot of these and below is sample code for what have worked best for me.

This should work regardless if it's a 32-bit or 64-bit application.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace WmiTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int processID = 12624;   // Change for the process you would like to use
            Process process = Process.GetProcessById(processID);
            string path = ProcessExecutablePath(process);
        }

        static private string ProcessExecutablePath(Process process)
        {
            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 "";
        }
    }
}

Note that you'll have to reference the System.Management assembly and use the System.Management namespace

Original source: https://stackoverflow.com/a/14668097/3850405

Ogglas
  • 62,132
  • 37
  • 328
  • 418