Search code examples
c#wpfwinformsnotepadwin32-process

How to get Notepad file saved location


How to retrieve the actual path of the notepad file if it is saved in drive. For example a notepad process is running and it is saved somewhere in the drive. How can I retrieve its full path? Using below code I can get the process detail, but not the actual path of particular files.

Process[] localByName = Process.GetProcessesByName("notepad");
foreach (Process p in localByName)
    {
      string path  =  p.MainModule.FileName.ToString();
    }

this returns executeable path but i need Drive location whre the actual file reside.


Solution

  • This should do it:

            string wmiQuery = string.Format("select CommandLine from Win32_Process where Name='{0}'", "notepad.exe");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
            ManagementObjectCollection retObjectCollection = searcher.Get();
            foreach (ManagementObject retObject in retObjectCollection)
            {
                string CommandLine = retObject["CommandLine"].ToString();
                string path = CommandLine.Substring(CommandLine.IndexOf(" ") + 1, CommandLine.Length - CommandLine.IndexOf(" ") - 1);
            }
    

    It will work only if the file is opened by double click or through command line.

    Don't forget to add reference to System.Management by right Click on Project, Add References then select the Assemblies Tab and Search for System.Management.

    Step 1

    Step 2