How to get parent process in .NET in managed way

后端 未结 6 671
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 03:39

I was looking a lot for method to get parent process in .NET, but found only P/Invoke way.

6条回答
  •  甜味超标
    2020-11-22 04:29

    This code provides a nice interface for finding the Parent process object and takes into account the possibility of multiple processes with the same name:

    Usage:

    Console.WriteLine("ParentPid: " + Process.GetProcessById(6972).Parent().Id);
    

    Code:

    public static class ProcessExtensions {
        private static string FindIndexedProcessName(int pid) {
            var processName = Process.GetProcessById(pid).ProcessName;
            var processesByName = Process.GetProcessesByName(processName);
            string processIndexdName = null;
    
            for (var index = 0; index < processesByName.Length; index++) {
                processIndexdName = index == 0 ? processName : processName + "#" + index;
                var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
                if ((int) processId.NextValue() == pid) {
                    return processIndexdName;
                }
            }
    
            return processIndexdName;
        }
    
        private static Process FindPidFromIndexedProcessName(string indexedProcessName) {
            var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
            return Process.GetProcessById((int) parentId.NextValue());
        }
    
        public static Process Parent(this Process process) {
            return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
        }
    }
    

提交回复
热议问题