mscorlib(4.0.0.0) API with additions
Process.cs
1 using Microsoft.Win32;
2 using Microsoft.Win32.SafeHandles;
3 using System.Collections;
7 using System.IO;
10 using System.Security;
12 using System.Text;
13 using System.Threading;
14 
15 namespace System.Diagnostics
16 {
18  [MonitoringDescription("ProcessDesc")]
19  [DefaultEvent("Exited")]
20  [DefaultProperty("StartInfo")]
21  [Designer("System.Diagnostics.Design.ProcessDesigner, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
22  [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
23  [HostProtection(SecurityAction.LinkDemand, SharedState = true, Synchronization = true, ExternalProcessMgmt = true, SelfAffectingProcessMgmt = true)]
24  [PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")]
25  public class Process : Component
26  {
27  private enum StreamReadMode
28  {
29  undefined,
30  syncMode,
31  asyncMode
32  }
33 
34  private enum State
35  {
36  HaveId = 1,
37  IsLocal = 2,
38  IsNt = 4,
39  HaveProcessInfo = 8,
40  Exited = 0x10,
41  Associated = 0x20,
42  IsWin2k = 0x40,
43  HaveNtProcessInfo = 12
44  }
45 
46  private bool haveProcessId;
47 
48  private int processId;
49 
50  private bool haveProcessHandle;
51 
52  private SafeProcessHandle m_processHandle;
53 
54  private bool isRemoteMachine;
55 
56  private string machineName;
57 
58  private ProcessInfo processInfo;
59 
60  private int m_processAccess;
61 
62  private ProcessThreadCollection threads;
63 
64  private ProcessModuleCollection modules;
65 
66  private bool haveMainWindow;
67 
68  private IntPtr mainWindowHandle;
69 
70  private string mainWindowTitle;
71 
72  private bool haveWorkingSetLimits;
73 
74  private IntPtr minWorkingSet;
75 
76  private IntPtr maxWorkingSet;
77 
78  private bool haveProcessorAffinity;
79 
80  private IntPtr processorAffinity;
81 
82  private bool havePriorityClass;
83 
84  private ProcessPriorityClass priorityClass;
85 
86  private ProcessStartInfo startInfo;
87 
88  private bool watchForExit;
89 
90  private bool watchingForExit;
91 
92  private EventHandler onExited;
93 
94  private bool exited;
95 
96  private int exitCode;
97 
98  private bool signaled;
99 
100  private DateTime exitTime;
101 
102  private bool haveExitTime;
103 
104  private bool responding;
105 
106  private bool haveResponding;
107 
108  private bool priorityBoostEnabled;
109 
110  private bool havePriorityBoostEnabled;
111 
112  private bool raisedOnExited;
113 
114  private RegisteredWaitHandle registeredWaitHandle;
115 
116  private WaitHandle waitHandle;
117 
118  private ISynchronizeInvoke synchronizingObject;
119 
120  private StreamReader standardOutput;
121 
122  private StreamWriter standardInput;
123 
124  private StreamReader standardError;
125 
126  private OperatingSystem operatingSystem;
127 
128  private bool disposed;
129 
130  private static object s_CreateProcessLock = new object();
131 
132  private StreamReadMode outputStreamReadMode;
133 
134  private StreamReadMode errorStreamReadMode;
135 
136  internal AsyncStreamReader output;
137 
138  internal AsyncStreamReader error;
139 
140  internal bool pendingOutputRead;
141 
142  internal bool pendingErrorRead;
143 
144  private static SafeFileHandle InvalidPipeHandle = new SafeFileHandle(IntPtr.Zero, ownsHandle: false);
145 
146  internal static TraceSwitch processTracing = null;
147 
148  [Browsable(false)]
150  [MonitoringDescription("ProcessAssociated")]
151  private bool Associated
152  {
153  get
154  {
155  if (!haveProcessId)
156  {
157  return haveProcessHandle;
158  }
159  return true;
160  }
161  }
162 
168  [MonitoringDescription("ProcessBasePriority")]
169  public int BasePriority
170  {
171  get
172  {
173  EnsureState(State.HaveProcessInfo);
174  return processInfo.basePriority;
175  }
176  }
177 
182  [Browsable(false)]
184  [MonitoringDescription("ProcessExitCode")]
185  public int ExitCode
186  {
187  get
188  {
189  EnsureState(State.Exited);
190  return exitCode;
191  }
192  }
193 
200  [Browsable(false)]
202  [MonitoringDescription("ProcessTerminated")]
203  public bool HasExited
204  {
205  get
206  {
207  if (!exited)
208  {
209  EnsureState(State.Associated);
210  SafeProcessHandle safeProcessHandle = null;
211  try
212  {
213  safeProcessHandle = GetProcessHandle(1049600, throwIfExited: false);
214  int num;
215  if (safeProcessHandle.IsInvalid)
216  {
217  exited = true;
218  }
219  else if (Microsoft.Win32.NativeMethods.GetExitCodeProcess(safeProcessHandle, out num) && num != 259)
220  {
221  exited = true;
222  exitCode = num;
223  }
224  else
225  {
226  if (!signaled)
227  {
228  ProcessWaitHandle processWaitHandle = null;
229  try
230  {
231  processWaitHandle = new ProcessWaitHandle(safeProcessHandle);
232  signaled = processWaitHandle.WaitOne(0, exitContext: false);
233  }
234  finally
235  {
236  processWaitHandle?.Close();
237  }
238  }
239  if (signaled)
240  {
241  if (!Microsoft.Win32.NativeMethods.GetExitCodeProcess(safeProcessHandle, out num))
242  {
243  throw new Win32Exception();
244  }
245  exited = true;
246  exitCode = num;
247  }
248  }
249  }
250  finally
251  {
252  ReleaseProcessHandle(safeProcessHandle);
253  }
254  if (exited)
255  {
256  RaiseOnExited();
257  }
258  }
259  return exited;
260  }
261  }
262 
267  [Browsable(false)]
269  [MonitoringDescription("ProcessExitTime")]
270  public DateTime ExitTime
271  {
272  get
273  {
274  if (!haveExitTime)
275  {
276  EnsureState((State)20);
277  exitTime = GetProcessTimes().ExitTime;
278  haveExitTime = true;
279  }
280  return exitTime;
281  }
282  }
283 
288  [Browsable(false)]
290  [MonitoringDescription("ProcessHandle")]
291  public IntPtr Handle
292  {
293  get
294  {
295  EnsureState(State.Associated);
296  return OpenProcessHandle(m_processAccess).DangerousGetHandle();
297  }
298  }
299 
302  [Browsable(false)]
304  public SafeProcessHandle SafeHandle
305  {
306  get
307  {
308  EnsureState(State.Associated);
309  return OpenProcessHandle(m_processAccess);
310  }
311  }
312 
317  [MonitoringDescription("ProcessHandleCount")]
318  public int HandleCount
319  {
320  get
321  {
322  EnsureState(State.HaveProcessInfo);
323  return processInfo.handleCount;
324  }
325  }
326 
332  [MonitoringDescription("ProcessId")]
333  public int Id
334  {
335  get
336  {
337  EnsureState(State.HaveId);
338  return processId;
339  }
340  }
341 
345  [Browsable(false)]
347  [MonitoringDescription("ProcessMachineName")]
348  public string MachineName
349  {
350  get
351  {
352  EnsureState(State.Associated);
353  return machineName;
354  }
355  }
356 
363  [MonitoringDescription("ProcessMainWindowHandle")]
364  public IntPtr MainWindowHandle
365  {
366  get
367  {
368  if (!haveMainWindow)
369  {
370  EnsureState((State)3);
371  mainWindowHandle = ProcessManager.GetMainWindowHandle(processId);
372  if (mainWindowHandle != (IntPtr)0)
373  {
374  haveMainWindow = true;
375  }
376  else
377  {
378  EnsureState(State.HaveProcessInfo);
379  }
380  }
381  return mainWindowHandle;
382  }
383  }
384 
391  [MonitoringDescription("ProcessMainWindowTitle")]
392  public string MainWindowTitle
393  {
394  get
395  {
396  if (mainWindowTitle == null)
397  {
398  IntPtr intPtr = MainWindowHandle;
399  if (intPtr == (IntPtr)0)
400  {
401  mainWindowTitle = string.Empty;
402  }
403  else
404  {
405  int capacity = Microsoft.Win32.NativeMethods.GetWindowTextLength(new HandleRef(this, intPtr)) * 2;
406  StringBuilder stringBuilder = new StringBuilder(capacity);
407  Microsoft.Win32.NativeMethods.GetWindowText(new HandleRef(this, intPtr), stringBuilder, stringBuilder.Capacity);
408  mainWindowTitle = stringBuilder.ToString();
409  }
410  }
411  return mainWindowTitle;
412  }
413  }
414 
421  [Browsable(false)]
423  [MonitoringDescription("ProcessMainModule")]
425  {
426  get
427  {
428  if (OperatingSystem.Platform == PlatformID.Win32NT)
429  {
430  EnsureState((State)3);
431  ModuleInfo firstModuleInfo = NtProcessManager.GetFirstModuleInfo(processId);
432  return new ProcessModule(firstModuleInfo);
433  }
434  ProcessModuleCollection processModuleCollection = Modules;
435  EnsureState(State.HaveProcessInfo);
436  foreach (ProcessModule item in processModuleCollection)
437  {
438  if (item.moduleInfo.Id == processInfo.mainModuleId)
439  {
440  return item;
441  }
442  }
443  return null;
444  }
445  }
446 
455  [MonitoringDescription("ProcessMaxWorkingSet")]
456  public IntPtr MaxWorkingSet
457  {
458  get
459  {
460  EnsureWorkingSetLimits();
461  return maxWorkingSet;
462  }
463  set
464  {
465  SetWorkingSetLimits(null, value);
466  }
467  }
468 
477  [MonitoringDescription("ProcessMinWorkingSet")]
478  public IntPtr MinWorkingSet
479  {
480  get
481  {
482  EnsureWorkingSetLimits();
483  return minWorkingSet;
484  }
485  set
486  {
487  SetWorkingSetLimits(value, null);
488  }
489  }
490 
497  [Browsable(false)]
499  [MonitoringDescription("ProcessModules")]
501  {
502  get
503  {
504  if (modules == null)
505  {
506  EnsureState((State)3);
507  ModuleInfo[] moduleInfos = ProcessManager.GetModuleInfos(processId);
508  ProcessModule[] array = new ProcessModule[moduleInfos.Length];
509  for (int i = 0; i < moduleInfos.Length; i++)
510  {
511  array[i] = new ProcessModule(moduleInfos[i]);
512  }
513  ProcessModuleCollection processModuleCollection = modules = new ProcessModuleCollection(array);
514  }
515  return modules;
516  }
517  }
518 
522  [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
524  [MonitoringDescription("ProcessNonpagedSystemMemorySize")]
525  public int NonpagedSystemMemorySize
526  {
527  get
528  {
529  EnsureState(State.HaveNtProcessInfo);
530  return (int)processInfo.poolNonpagedBytes;
531  }
532  }
533 
538  [MonitoringDescription("ProcessNonpagedSystemMemorySize")]
539  [ComVisible(false)]
540  public long NonpagedSystemMemorySize64
541  {
542  get
543  {
544  EnsureState(State.HaveNtProcessInfo);
545  return processInfo.poolNonpagedBytes;
546  }
547  }
548 
552  [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
554  [MonitoringDescription("ProcessPagedMemorySize")]
555  public int PagedMemorySize
556  {
557  get
558  {
559  EnsureState(State.HaveNtProcessInfo);
560  return (int)processInfo.pageFileBytes;
561  }
562  }
563 
568  [MonitoringDescription("ProcessPagedMemorySize")]
569  [ComVisible(false)]
570  public long PagedMemorySize64
571  {
572  get
573  {
574  EnsureState(State.HaveNtProcessInfo);
575  return processInfo.pageFileBytes;
576  }
577  }
578 
582  [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
584  [MonitoringDescription("ProcessPagedSystemMemorySize")]
585  public int PagedSystemMemorySize
586  {
587  get
588  {
589  EnsureState(State.HaveNtProcessInfo);
590  return (int)processInfo.poolPagedBytes;
591  }
592  }
593 
598  [MonitoringDescription("ProcessPagedSystemMemorySize")]
599  [ComVisible(false)]
600  public long PagedSystemMemorySize64
601  {
602  get
603  {
604  EnsureState(State.HaveNtProcessInfo);
605  return processInfo.poolPagedBytes;
606  }
607  }
608 
612  [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
614  [MonitoringDescription("ProcessPeakPagedMemorySize")]
615  public int PeakPagedMemorySize
616  {
617  get
618  {
619  EnsureState(State.HaveNtProcessInfo);
620  return (int)processInfo.pageFileBytesPeak;
621  }
622  }
623 
628  [MonitoringDescription("ProcessPeakPagedMemorySize")]
629  [ComVisible(false)]
630  public long PeakPagedMemorySize64
631  {
632  get
633  {
634  EnsureState(State.HaveNtProcessInfo);
635  return processInfo.pageFileBytesPeak;
636  }
637  }
638 
642  [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
644  [MonitoringDescription("ProcessPeakWorkingSet")]
645  public int PeakWorkingSet
646  {
647  get
648  {
649  EnsureState(State.HaveNtProcessInfo);
650  return (int)processInfo.workingSetPeak;
651  }
652  }
653 
658  [MonitoringDescription("ProcessPeakWorkingSet")]
659  [ComVisible(false)]
660  public long PeakWorkingSet64
661  {
662  get
663  {
664  EnsureState(State.HaveNtProcessInfo);
665  return processInfo.workingSetPeak;
666  }
667  }
668 
672  [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
674  [MonitoringDescription("ProcessPeakVirtualMemorySize")]
675  public int PeakVirtualMemorySize
676  {
677  get
678  {
679  EnsureState(State.HaveNtProcessInfo);
680  return (int)processInfo.virtualBytesPeak;
681  }
682  }
683 
688  [MonitoringDescription("ProcessPeakVirtualMemorySize")]
689  [ComVisible(false)]
690  public long PeakVirtualMemorySize64
691  {
692  get
693  {
694  EnsureState(State.HaveNtProcessInfo);
695  return processInfo.virtualBytesPeak;
696  }
697  }
698 
700  {
701  get
702  {
703  if (operatingSystem == null)
704  {
705  operatingSystem = Environment.OSVersion;
706  }
707  return operatingSystem;
708  }
709  }
710 
719  [MonitoringDescription("ProcessPriorityBoostEnabled")]
720  public bool PriorityBoostEnabled
721  {
722  get
723  {
724  EnsureState(State.IsNt);
725  if (!havePriorityBoostEnabled)
726  {
727  SafeProcessHandle handle = null;
728  try
729  {
730  handle = GetProcessHandle(1024);
731  bool disabled = false;
732  if (!Microsoft.Win32.NativeMethods.GetProcessPriorityBoost(handle, out disabled))
733  {
734  throw new Win32Exception();
735  }
736  priorityBoostEnabled = !disabled;
737  havePriorityBoostEnabled = true;
738  }
739  finally
740  {
741  ReleaseProcessHandle(handle);
742  }
743  }
744  return priorityBoostEnabled;
745  }
746  set
747  {
748  EnsureState(State.IsNt);
749  SafeProcessHandle handle = null;
750  try
751  {
752  handle = GetProcessHandle(512);
753  if (!Microsoft.Win32.NativeMethods.SetProcessPriorityBoost(handle, !value))
754  {
755  throw new Win32Exception();
756  }
757  priorityBoostEnabled = value;
758  havePriorityBoostEnabled = true;
759  }
760  finally
761  {
762  ReleaseProcessHandle(handle);
763  }
764  }
765  }
766 
775  [MonitoringDescription("ProcessPriorityClass")]
777  {
778  get
779  {
780  if (!havePriorityClass)
781  {
782  SafeProcessHandle handle = null;
783  try
784  {
785  handle = GetProcessHandle(1024);
786  int num = Microsoft.Win32.NativeMethods.GetPriorityClass(handle);
787  if (num == 0)
788  {
789  throw new Win32Exception();
790  }
791  priorityClass = (ProcessPriorityClass)num;
792  havePriorityClass = true;
793  }
794  finally
795  {
796  ReleaseProcessHandle(handle);
797  }
798  }
799  return priorityClass;
800  }
801  set
802  {
803  if (!Enum.IsDefined(typeof(ProcessPriorityClass), value))
804  {
805  throw new InvalidEnumArgumentException("value", (int)value, typeof(ProcessPriorityClass));
806  }
807  if ((value & (ProcessPriorityClass)49152) != 0 && (OperatingSystem.Platform != PlatformID.Win32NT || OperatingSystem.Version.Major < 5))
808  {
809  throw new PlatformNotSupportedException(SR.GetString("PriorityClassNotSupported"), null);
810  }
811  SafeProcessHandle handle = null;
812  try
813  {
814  handle = GetProcessHandle(512);
815  if (!Microsoft.Win32.NativeMethods.SetPriorityClass(handle, (int)value))
816  {
817  throw new Win32Exception();
818  }
819  priorityClass = value;
820  havePriorityClass = true;
821  }
822  finally
823  {
824  ReleaseProcessHandle(handle);
825  }
826  }
827  }
828 
832  [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
834  [MonitoringDescription("ProcessPrivateMemorySize")]
835  public int PrivateMemorySize
836  {
837  get
838  {
839  EnsureState(State.HaveNtProcessInfo);
840  return (int)processInfo.privateBytes;
841  }
842  }
843 
848  [MonitoringDescription("ProcessPrivateMemorySize")]
849  [ComVisible(false)]
850  public long PrivateMemorySize64
851  {
852  get
853  {
854  EnsureState(State.HaveNtProcessInfo);
855  return processInfo.privateBytes;
856  }
857  }
858 
864  [MonitoringDescription("ProcessPrivilegedProcessorTime")]
866  {
867  get
868  {
869  EnsureState(State.IsNt);
870  return GetProcessTimes().PrivilegedProcessorTime;
871  }
872  }
873 
880  [MonitoringDescription("ProcessProcessName")]
881  public string ProcessName
882  {
883  get
884  {
885  EnsureState(State.HaveProcessInfo);
886  string processName = processInfo.processName;
887  if (processName.Length == 15 && ProcessManager.IsNt && ProcessManager.IsOSOlderThanXP && !isRemoteMachine)
888  {
889  try
890  {
891  string moduleName = MainModule.ModuleName;
892  if (moduleName != null)
893  {
894  processInfo.processName = Path.ChangeExtension(Path.GetFileName(moduleName), null);
895  }
896  }
897  catch (Exception)
898  {
899  }
900  }
901  return processInfo.processName;
902  }
903  }
904 
912  [MonitoringDescription("ProcessProcessorAffinity")]
914  {
915  get
916  {
917  if (!haveProcessorAffinity)
918  {
919  SafeProcessHandle handle = null;
920  try
921  {
922  handle = GetProcessHandle(1024);
923  if (!Microsoft.Win32.NativeMethods.GetProcessAffinityMask(handle, out IntPtr processMask, out IntPtr _))
924  {
925  throw new Win32Exception();
926  }
927  processorAffinity = processMask;
928  }
929  finally
930  {
931  ReleaseProcessHandle(handle);
932  }
933  haveProcessorAffinity = true;
934  }
935  return processorAffinity;
936  }
937  set
938  {
939  SafeProcessHandle handle = null;
940  try
941  {
942  handle = GetProcessHandle(512);
943  if (!Microsoft.Win32.NativeMethods.SetProcessAffinityMask(handle, value))
944  {
945  throw new Win32Exception();
946  }
947  processorAffinity = value;
948  haveProcessorAffinity = true;
949  }
950  finally
951  {
952  ReleaseProcessHandle(handle);
953  }
954  }
955  }
956 
964  [MonitoringDescription("ProcessResponding")]
965  public bool Responding
966  {
967  get
968  {
969  if (!haveResponding)
970  {
971  IntPtr intPtr = MainWindowHandle;
972  if (intPtr == (IntPtr)0)
973  {
974  responding = true;
975  }
976  else
977  {
978  responding = (Microsoft.Win32.NativeMethods.SendMessageTimeout(new HandleRef(this, intPtr), 0, IntPtr.Zero, IntPtr.Zero, 2, 5000, out IntPtr _) != (IntPtr)0);
979  }
980  }
981  return responding;
982  }
983  }
984 
991  [MonitoringDescription("ProcessSessionId")]
992  public int SessionId
993  {
994  get
995  {
996  EnsureState(State.HaveNtProcessInfo);
997  return processInfo.sessionId;
998  }
999  }
1000 
1004  [Browsable(false)]
1006  [MonitoringDescription("ProcessStartInfo")]
1008  {
1009  get
1010  {
1011  if (startInfo == null)
1012  {
1013  startInfo = new ProcessStartInfo(this);
1014  }
1015  return startInfo;
1016  }
1017  set
1018  {
1019  if (value == null)
1020  {
1021  throw new ArgumentNullException("value");
1022  }
1023  startInfo = value;
1024  }
1025  }
1026 
1034  [MonitoringDescription("ProcessStartTime")]
1035  public DateTime StartTime
1036  {
1037  get
1038  {
1039  EnsureState(State.IsNt);
1040  return GetProcessTimes().StartTime;
1041  }
1042  }
1043 
1046  [Browsable(false)]
1047  [DefaultValue(null)]
1048  [MonitoringDescription("ProcessSynchronizingObject")]
1050  {
1051  get
1052  {
1053  if (synchronizingObject == null && base.DesignMode)
1054  {
1055  IDesignerHost designerHost = (IDesignerHost)GetService(typeof(IDesignerHost));
1056  if (designerHost != null)
1057  {
1058  object rootComponent = designerHost.RootComponent;
1059  if (rootComponent != null && rootComponent is ISynchronizeInvoke)
1060  {
1061  synchronizingObject = (ISynchronizeInvoke)rootComponent;
1062  }
1063  }
1064  }
1065  return synchronizingObject;
1066  }
1067  set
1068  {
1069  synchronizingObject = value;
1070  }
1071  }
1072 
1077  [Browsable(false)]
1079  [MonitoringDescription("ProcessThreads")]
1081  {
1082  get
1083  {
1084  if (threads == null)
1085  {
1086  EnsureState(State.HaveProcessInfo);
1087  int count = processInfo.threadInfoList.Count;
1088  ProcessThread[] array = new ProcessThread[count];
1089  for (int i = 0; i < count; i++)
1090  {
1091  array[i] = new ProcessThread(isRemoteMachine, (ThreadInfo)processInfo.threadInfoList[i]);
1092  }
1093  ProcessThreadCollection processThreadCollection = threads = new ProcessThreadCollection(array);
1094  }
1095  return threads;
1096  }
1097  }
1098 
1104  [MonitoringDescription("ProcessTotalProcessorTime")]
1106  {
1107  get
1108  {
1109  EnsureState(State.IsNt);
1110  return GetProcessTimes().TotalProcessorTime;
1111  }
1112  }
1113 
1119  [MonitoringDescription("ProcessUserProcessorTime")]
1121  {
1122  get
1123  {
1124  EnsureState(State.IsNt);
1125  return GetProcessTimes().UserProcessorTime;
1126  }
1127  }
1128 
1132  [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
1134  [MonitoringDescription("ProcessVirtualMemorySize")]
1135  public int VirtualMemorySize
1136  {
1137  get
1138  {
1139  EnsureState(State.HaveNtProcessInfo);
1140  return (int)processInfo.virtualBytes;
1141  }
1142  }
1143 
1148  [MonitoringDescription("ProcessVirtualMemorySize")]
1149  [ComVisible(false)]
1150  public long VirtualMemorySize64
1151  {
1152  get
1153  {
1154  EnsureState(State.HaveNtProcessInfo);
1155  return processInfo.virtualBytes;
1156  }
1157  }
1158 
1162  [Browsable(false)]
1163  [DefaultValue(false)]
1164  [MonitoringDescription("ProcessEnableRaisingEvents")]
1165  public bool EnableRaisingEvents
1166  {
1167  get
1168  {
1169  return watchForExit;
1170  }
1171  set
1172  {
1173  if (value == watchForExit)
1174  {
1175  return;
1176  }
1177  if (Associated)
1178  {
1179  if (value)
1180  {
1181  OpenProcessHandle();
1182  EnsureWatchingForExit();
1183  }
1184  else
1185  {
1186  StopWatchingForExit();
1187  }
1188  }
1189  watchForExit = value;
1190  }
1191  }
1192 
1196  [Browsable(false)]
1198  [MonitoringDescription("ProcessStandardInput")]
1200  {
1201  get
1202  {
1203  if (standardInput == null)
1204  {
1205  throw new InvalidOperationException(SR.GetString("CantGetStandardIn"));
1206  }
1207  return standardInput;
1208  }
1209  }
1210 
1214  [Browsable(false)]
1216  [MonitoringDescription("ProcessStandardOutput")]
1218  {
1219  get
1220  {
1221  if (standardOutput == null)
1222  {
1223  throw new InvalidOperationException(SR.GetString("CantGetStandardOut"));
1224  }
1225  if (outputStreamReadMode == StreamReadMode.undefined)
1226  {
1227  outputStreamReadMode = StreamReadMode.syncMode;
1228  }
1229  else if (outputStreamReadMode != StreamReadMode.syncMode)
1230  {
1231  throw new InvalidOperationException(SR.GetString("CantMixSyncAsyncOperation"));
1232  }
1233  return standardOutput;
1234  }
1235  }
1236 
1240  [Browsable(false)]
1242  [MonitoringDescription("ProcessStandardError")]
1244  {
1245  get
1246  {
1247  if (standardError == null)
1248  {
1249  throw new InvalidOperationException(SR.GetString("CantGetStandardError"));
1250  }
1251  if (errorStreamReadMode == StreamReadMode.undefined)
1252  {
1253  errorStreamReadMode = StreamReadMode.syncMode;
1254  }
1255  else if (errorStreamReadMode != StreamReadMode.syncMode)
1256  {
1257  throw new InvalidOperationException(SR.GetString("CantMixSyncAsyncOperation"));
1258  }
1259  return standardError;
1260  }
1261  }
1262 
1266  [Obsolete("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
1268  [MonitoringDescription("ProcessWorkingSet")]
1269  public int WorkingSet
1270  {
1271  get
1272  {
1273  EnsureState(State.HaveNtProcessInfo);
1274  return (int)processInfo.workingSet;
1275  }
1276  }
1277 
1282  [MonitoringDescription("ProcessWorkingSet")]
1283  [ComVisible(false)]
1284  public long WorkingSet64
1285  {
1286  get
1287  {
1288  EnsureState(State.HaveNtProcessInfo);
1289  return processInfo.workingSet;
1290  }
1291  }
1292 
1294  [Browsable(true)]
1295  [MonitoringDescription("ProcessAssociated")]
1297 
1299  [Browsable(true)]
1300  [MonitoringDescription("ProcessAssociated")]
1302 
1304  [Category("Behavior")]
1305  [MonitoringDescription("ProcessExited")]
1306  public event EventHandler Exited
1307  {
1308  add
1309  {
1310  onExited = (EventHandler)Delegate.Combine(onExited, value);
1311  }
1312  remove
1313  {
1314  onExited = (EventHandler)Delegate.Remove(onExited, value);
1315  }
1316  }
1317 
1319  public Process()
1320  {
1321  machineName = ".";
1322  outputStreamReadMode = StreamReadMode.undefined;
1323  errorStreamReadMode = StreamReadMode.undefined;
1324  m_processAccess = 2035711;
1325  }
1326 
1327  private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo)
1328  {
1329  this.processInfo = processInfo;
1330  this.machineName = machineName;
1331  this.isRemoteMachine = isRemoteMachine;
1332  this.processId = processId;
1333  haveProcessId = true;
1334  outputStreamReadMode = StreamReadMode.undefined;
1335  errorStreamReadMode = StreamReadMode.undefined;
1336  m_processAccess = 2035711;
1337  }
1338 
1339  private ProcessThreadTimes GetProcessTimes()
1340  {
1341  ProcessThreadTimes processThreadTimes = new ProcessThreadTimes();
1342  SafeProcessHandle safeProcessHandle = null;
1343  try
1344  {
1345  int access = 1024;
1346  if (EnvironmentHelpers.IsWindowsVistaOrAbove())
1347  {
1348  access = 4096;
1349  }
1350  safeProcessHandle = GetProcessHandle(access, throwIfExited: false);
1351  if (safeProcessHandle.IsInvalid)
1352  {
1353  throw new InvalidOperationException(SR.GetString("ProcessHasExited", processId.ToString(CultureInfo.CurrentCulture)));
1354  }
1355  if (!Microsoft.Win32.NativeMethods.GetProcessTimes(safeProcessHandle, out processThreadTimes.create, out processThreadTimes.exit, out processThreadTimes.kernel, out processThreadTimes.user))
1356  {
1357  throw new Win32Exception();
1358  }
1359  return processThreadTimes;
1360  }
1361  finally
1362  {
1363  ReleaseProcessHandle(safeProcessHandle);
1364  }
1365  }
1366 
1372  public bool CloseMainWindow()
1373  {
1374  IntPtr intPtr = MainWindowHandle;
1375  if (intPtr == (IntPtr)0)
1376  {
1377  return false;
1378  }
1379  int windowLong = Microsoft.Win32.NativeMethods.GetWindowLong(new HandleRef(this, intPtr), -16);
1380  if ((windowLong & 0x8000000) != 0)
1381  {
1382  return false;
1383  }
1384  Microsoft.Win32.NativeMethods.PostMessage(new HandleRef(this, intPtr), 16, IntPtr.Zero, IntPtr.Zero);
1385  return true;
1386  }
1387 
1388  private void ReleaseProcessHandle(SafeProcessHandle handle)
1389  {
1390  if (handle != null && (!haveProcessHandle || handle != m_processHandle))
1391  {
1392  handle.Close();
1393  }
1394  }
1395 
1396  private void CompletionCallback(object context, bool wasSignaled)
1397  {
1398  StopWatchingForExit();
1399  RaiseOnExited();
1400  }
1401 
1405  protected override void Dispose(bool disposing)
1406  {
1407  if (!disposed)
1408  {
1409  if (disposing)
1410  {
1411  Close();
1412  }
1413  disposed = true;
1414  base.Dispose(disposing);
1415  }
1416  }
1417 
1419  public void Close()
1420  {
1421  if (Associated)
1422  {
1423  if (haveProcessHandle)
1424  {
1425  StopWatchingForExit();
1426  m_processHandle.Close();
1427  m_processHandle = null;
1428  haveProcessHandle = false;
1429  }
1430  haveProcessId = false;
1431  isRemoteMachine = false;
1432  machineName = ".";
1433  raisedOnExited = false;
1434  standardOutput = null;
1435  standardInput = null;
1436  standardError = null;
1437  output = null;
1438  error = null;
1439  Refresh();
1440  }
1441  }
1442 
1443  private void EnsureState(State state)
1444  {
1445  if ((state & State.IsWin2k) != 0 && (OperatingSystem.Platform != PlatformID.Win32NT || OperatingSystem.Version.Major < 5))
1446  {
1447  throw new PlatformNotSupportedException(SR.GetString("Win2kRequired"));
1448  }
1449  if ((state & State.IsNt) != 0 && OperatingSystem.Platform != PlatformID.Win32NT)
1450  {
1451  throw new PlatformNotSupportedException(SR.GetString("WinNTRequired"));
1452  }
1453  if ((state & State.Associated) != 0 && !Associated)
1454  {
1455  throw new InvalidOperationException(SR.GetString("NoAssociatedProcess"));
1456  }
1457  if ((state & State.HaveId) != 0 && !haveProcessId)
1458  {
1459  if (!haveProcessHandle)
1460  {
1461  EnsureState(State.Associated);
1462  throw new InvalidOperationException(SR.GetString("ProcessIdRequired"));
1463  }
1464  SetProcessId(ProcessManager.GetProcessIdFromHandle(m_processHandle));
1465  }
1466  if ((state & State.IsLocal) != 0 && isRemoteMachine)
1467  {
1468  throw new NotSupportedException(SR.GetString("NotSupportedRemote"));
1469  }
1470  if ((state & State.HaveProcessInfo) != 0 && processInfo == null)
1471  {
1472  if ((state & State.HaveId) == (State)0)
1473  {
1474  EnsureState(State.HaveId);
1475  }
1476  ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
1477  for (int i = 0; i < processInfos.Length; i++)
1478  {
1479  if (processInfos[i].processId == processId)
1480  {
1481  processInfo = processInfos[i];
1482  break;
1483  }
1484  }
1485  if (processInfo == null)
1486  {
1487  throw new InvalidOperationException(SR.GetString("NoProcessInfo"));
1488  }
1489  }
1490  if ((state & State.Exited) != 0)
1491  {
1492  if (!HasExited)
1493  {
1494  throw new InvalidOperationException(SR.GetString("WaitTillExit"));
1495  }
1496  if (!haveProcessHandle)
1497  {
1498  throw new InvalidOperationException(SR.GetString("NoProcessHandle"));
1499  }
1500  }
1501  }
1502 
1503  private void EnsureWatchingForExit()
1504  {
1505  if (!watchingForExit)
1506  {
1507  lock (this)
1508  {
1509  if (!watchingForExit)
1510  {
1511  watchingForExit = true;
1512  try
1513  {
1514  waitHandle = new ProcessWaitHandle(m_processHandle);
1515  registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(waitHandle, CompletionCallback, null, -1, executeOnlyOnce: true);
1516  }
1517  catch
1518  {
1519  watchingForExit = false;
1520  throw;
1521  }
1522  }
1523  }
1524  }
1525  }
1526 
1527  private void EnsureWorkingSetLimits()
1528  {
1529  EnsureState(State.IsNt);
1530  if (!haveWorkingSetLimits)
1531  {
1532  SafeProcessHandle handle = null;
1533  try
1534  {
1535  handle = GetProcessHandle(1024);
1536  if (!Microsoft.Win32.NativeMethods.GetProcessWorkingSetSize(handle, out IntPtr min, out IntPtr max))
1537  {
1538  throw new Win32Exception();
1539  }
1540  minWorkingSet = min;
1541  maxWorkingSet = max;
1542  haveWorkingSetLimits = true;
1543  }
1544  finally
1545  {
1546  ReleaseProcessHandle(handle);
1547  }
1548  }
1549  }
1550 
1552  public static void EnterDebugMode()
1553  {
1554  if (ProcessManager.IsNt)
1555  {
1556  SetPrivilege("SeDebugPrivilege", 2);
1557  }
1558  }
1559 
1560  private static void SetPrivilege(string privilegeName, int attrib)
1561  {
1562  IntPtr TokenHandle = (IntPtr)0;
1563  Microsoft.Win32.NativeMethods.LUID lpLuid = default(Microsoft.Win32.NativeMethods.LUID);
1564  IntPtr currentProcess = Microsoft.Win32.NativeMethods.GetCurrentProcess();
1565  if (!Microsoft.Win32.NativeMethods.OpenProcessToken(new HandleRef(null, currentProcess), 32, out TokenHandle))
1566  {
1567  throw new Win32Exception();
1568  }
1569  try
1570  {
1571  if (!Microsoft.Win32.NativeMethods.LookupPrivilegeValue(null, privilegeName, out lpLuid))
1572  {
1573  throw new Win32Exception();
1574  }
1575  Microsoft.Win32.NativeMethods.TokenPrivileges tokenPrivileges = new Microsoft.Win32.NativeMethods.TokenPrivileges();
1576  tokenPrivileges.Luid = lpLuid;
1577  tokenPrivileges.Attributes = attrib;
1578  Microsoft.Win32.NativeMethods.AdjustTokenPrivileges(new HandleRef(null, TokenHandle), DisableAllPrivileges: false, tokenPrivileges, 0, IntPtr.Zero, IntPtr.Zero);
1579  if (Marshal.GetLastWin32Error() != 0)
1580  {
1581  throw new Win32Exception();
1582  }
1583  }
1584  finally
1585  {
1586  Microsoft.Win32.SafeNativeMethods.CloseHandle(TokenHandle);
1587  }
1588  }
1589 
1591  public static void LeaveDebugMode()
1592  {
1593  if (ProcessManager.IsNt)
1594  {
1595  SetPrivilege("SeDebugPrivilege", 0);
1596  }
1597  }
1598 
1606  public static Process GetProcessById(int processId, string machineName)
1607  {
1608  if (!ProcessManager.IsProcessRunning(processId, machineName))
1609  {
1610  throw new ArgumentException(SR.GetString("MissingProccess", processId.ToString(CultureInfo.CurrentCulture)));
1611  }
1612  return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null);
1613  }
1614 
1620  public static Process GetProcessById(int processId)
1621  {
1622  return GetProcessById(processId, ".");
1623  }
1624 
1629  public static Process[] GetProcessesByName(string processName)
1630  {
1631  return GetProcessesByName(processName, ".");
1632  }
1633 
1643  public static Process[] GetProcessesByName(string processName, string machineName)
1644  {
1645  if (processName == null)
1646  {
1647  processName = string.Empty;
1648  }
1649  Process[] processes = GetProcesses(machineName);
1650  ArrayList arrayList = new ArrayList();
1651  for (int i = 0; i < processes.Length; i++)
1652  {
1653  if (string.Equals(processName, processes[i].ProcessName, StringComparison.OrdinalIgnoreCase))
1654  {
1655  arrayList.Add(processes[i]);
1656  }
1657  else
1658  {
1659  processes[i].Dispose();
1660  }
1661  }
1662  Process[] array = new Process[arrayList.Count];
1663  arrayList.CopyTo(array, 0);
1664  return array;
1665  }
1666 
1669  public static Process[] GetProcesses()
1670  {
1671  return GetProcesses(".");
1672  }
1673 
1682  public static Process[] GetProcesses(string machineName)
1683  {
1684  bool flag = ProcessManager.IsRemoteMachine(machineName);
1685  ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
1686  Process[] array = new Process[processInfos.Length];
1687  for (int i = 0; i < processInfos.Length; i++)
1688  {
1689  ProcessInfo processInfo = processInfos[i];
1690  array[i] = new Process(machineName, flag, processInfo.processId, processInfo);
1691  }
1692  return array;
1693  }
1694 
1697  public static Process GetCurrentProcess()
1698  {
1699  return new Process(".", isRemoteMachine: false, Microsoft.Win32.NativeMethods.GetCurrentProcessId(), null);
1700  }
1701 
1703  protected void OnExited()
1704  {
1705  EventHandler eventHandler = onExited;
1706  if (eventHandler != null)
1707  {
1709  {
1710  SynchronizingObject.BeginInvoke(eventHandler, new object[2]
1711  {
1712  this,
1714  });
1715  }
1716  else
1717  {
1718  eventHandler(this, EventArgs.Empty);
1719  }
1720  }
1721  }
1722 
1723  private SafeProcessHandle GetProcessHandle(int access, bool throwIfExited)
1724  {
1725  if (haveProcessHandle)
1726  {
1727  if (throwIfExited)
1728  {
1729  ProcessWaitHandle processWaitHandle = null;
1730  try
1731  {
1732  processWaitHandle = new ProcessWaitHandle(m_processHandle);
1733  if (processWaitHandle.WaitOne(0, exitContext: false))
1734  {
1735  if (haveProcessId)
1736  {
1737  throw new InvalidOperationException(SR.GetString("ProcessHasExited", processId.ToString(CultureInfo.CurrentCulture)));
1738  }
1739  throw new InvalidOperationException(SR.GetString("ProcessHasExitedNoId"));
1740  }
1741  }
1742  finally
1743  {
1744  processWaitHandle?.Close();
1745  }
1746  }
1747  return m_processHandle;
1748  }
1749  EnsureState((State)3);
1750  SafeProcessHandle invalidHandle = SafeProcessHandle.InvalidHandle;
1751  invalidHandle = ProcessManager.OpenProcess(processId, access, throwIfExited);
1752  if (throwIfExited && (access & 0x400) != 0 && Microsoft.Win32.NativeMethods.GetExitCodeProcess(invalidHandle, out exitCode) && exitCode != 259)
1753  {
1754  throw new InvalidOperationException(SR.GetString("ProcessHasExited", processId.ToString(CultureInfo.CurrentCulture)));
1755  }
1756  return invalidHandle;
1757  }
1758 
1759  private SafeProcessHandle GetProcessHandle(int access)
1760  {
1761  return GetProcessHandle(access, throwIfExited: true);
1762  }
1763 
1764  private SafeProcessHandle OpenProcessHandle()
1765  {
1766  return OpenProcessHandle(2035711);
1767  }
1768 
1769  private SafeProcessHandle OpenProcessHandle(int access)
1770  {
1771  if (!haveProcessHandle)
1772  {
1773  if (disposed)
1774  {
1775  throw new ObjectDisposedException(GetType().Name);
1776  }
1777  SetProcessHandle(GetProcessHandle(access));
1778  }
1779  return m_processHandle;
1780  }
1781 
1782  private void RaiseOnExited()
1783  {
1784  if (!raisedOnExited)
1785  {
1786  lock (this)
1787  {
1788  if (!raisedOnExited)
1789  {
1790  raisedOnExited = true;
1791  OnExited();
1792  }
1793  }
1794  }
1795  }
1796 
1798  public void Refresh()
1799  {
1800  processInfo = null;
1801  threads = null;
1802  modules = null;
1803  mainWindowTitle = null;
1804  exited = false;
1805  signaled = false;
1806  haveMainWindow = false;
1807  haveWorkingSetLimits = false;
1808  haveProcessorAffinity = false;
1809  havePriorityClass = false;
1810  haveExitTime = false;
1811  haveResponding = false;
1812  havePriorityBoostEnabled = false;
1813  }
1814 
1815  private void SetProcessHandle(SafeProcessHandle processHandle)
1816  {
1817  m_processHandle = processHandle;
1818  haveProcessHandle = true;
1819  if (watchForExit)
1820  {
1821  EnsureWatchingForExit();
1822  }
1823  }
1824 
1825  private void SetProcessId(int processId)
1826  {
1827  this.processId = processId;
1828  haveProcessId = true;
1829  }
1830 
1831  private void SetWorkingSetLimits(object newMin, object newMax)
1832  {
1833  EnsureState(State.IsNt);
1834  SafeProcessHandle handle = null;
1835  try
1836  {
1837  handle = GetProcessHandle(1280);
1838  if (!Microsoft.Win32.NativeMethods.GetProcessWorkingSetSize(handle, out IntPtr min, out IntPtr max))
1839  {
1840  throw new Win32Exception();
1841  }
1842  if (newMin != null)
1843  {
1844  min = (IntPtr)newMin;
1845  }
1846  if (newMax != null)
1847  {
1848  max = (IntPtr)newMax;
1849  }
1850  if ((long)min > (long)max)
1851  {
1852  if (newMin != null)
1853  {
1854  throw new ArgumentException(SR.GetString("BadMinWorkset"));
1855  }
1856  throw new ArgumentException(SR.GetString("BadMaxWorkset"));
1857  }
1858  if (!Microsoft.Win32.NativeMethods.SetProcessWorkingSetSize(handle, min, max))
1859  {
1860  throw new Win32Exception();
1861  }
1862  if (!Microsoft.Win32.NativeMethods.GetProcessWorkingSetSize(handle, out min, out max))
1863  {
1864  throw new Win32Exception();
1865  }
1866  minWorkingSet = min;
1867  maxWorkingSet = max;
1868  haveWorkingSetLimits = true;
1869  }
1870  finally
1871  {
1872  ReleaseProcessHandle(handle);
1873  }
1874  }
1875 
1882  public bool Start()
1883  {
1884  Close();
1885  ProcessStartInfo processStartInfo = StartInfo;
1886  if (processStartInfo.FileName.Length == 0)
1887  {
1888  throw new InvalidOperationException(SR.GetString("FileNameMissing"));
1889  }
1890  if (processStartInfo.UseShellExecute)
1891  {
1892  return StartWithShellExecuteEx(processStartInfo);
1893  }
1894  return StartWithCreateProcess(processStartInfo);
1895  }
1896 
1897  private static void CreatePipeWithSecurityAttributes(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, Microsoft.Win32.NativeMethods.SECURITY_ATTRIBUTES lpPipeAttributes, int nSize)
1898  {
1899  if (!Microsoft.Win32.NativeMethods.CreatePipe(out hReadPipe, out hWritePipe, lpPipeAttributes, nSize) || hReadPipe.IsInvalid || hWritePipe.IsInvalid)
1900  {
1901  throw new Win32Exception();
1902  }
1903  }
1904 
1905  private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs)
1906  {
1907  Microsoft.Win32.NativeMethods.SECURITY_ATTRIBUTES sECURITY_ATTRIBUTES = new Microsoft.Win32.NativeMethods.SECURITY_ATTRIBUTES();
1908  sECURITY_ATTRIBUTES.bInheritHandle = true;
1909  SafeFileHandle hWritePipe = null;
1910  try
1911  {
1912  if (parentInputs)
1913  {
1914  CreatePipeWithSecurityAttributes(out childHandle, out hWritePipe, sECURITY_ATTRIBUTES, 0);
1915  }
1916  else
1917  {
1918  CreatePipeWithSecurityAttributes(out hWritePipe, out childHandle, sECURITY_ATTRIBUTES, 0);
1919  }
1920  if (!Microsoft.Win32.NativeMethods.DuplicateHandle(new HandleRef(this, Microsoft.Win32.NativeMethods.GetCurrentProcess()), hWritePipe, new HandleRef(this, Microsoft.Win32.NativeMethods.GetCurrentProcess()), out parentHandle, 0, bInheritHandle: false, 2))
1921  {
1922  throw new Win32Exception();
1923  }
1924  }
1925  finally
1926  {
1927  if (hWritePipe != null && !hWritePipe.IsInvalid)
1928  {
1929  hWritePipe.Close();
1930  }
1931  }
1932  }
1933 
1934  private static StringBuilder BuildCommandLine(string executableFileName, string arguments)
1935  {
1936  StringBuilder stringBuilder = new StringBuilder();
1937  string text = executableFileName.Trim();
1938  bool flag = text.StartsWith("\"", StringComparison.Ordinal) && text.EndsWith("\"", StringComparison.Ordinal);
1939  if (!flag)
1940  {
1941  stringBuilder.Append("\"");
1942  }
1943  stringBuilder.Append(text);
1944  if (!flag)
1945  {
1946  stringBuilder.Append("\"");
1947  }
1948  if (!string.IsNullOrEmpty(arguments))
1949  {
1950  stringBuilder.Append(" ");
1951  stringBuilder.Append(arguments);
1952  }
1953  return stringBuilder;
1954  }
1955 
1956  private bool StartWithCreateProcess(ProcessStartInfo startInfo)
1957  {
1958  if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput)
1959  {
1960  throw new InvalidOperationException(SR.GetString("StandardOutputEncodingNotAllowed"));
1961  }
1962  if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError)
1963  {
1964  throw new InvalidOperationException(SR.GetString("StandardErrorEncodingNotAllowed"));
1965  }
1966  if (disposed)
1967  {
1968  throw new ObjectDisposedException(GetType().Name);
1969  }
1970  StringBuilder stringBuilder = BuildCommandLine(startInfo.FileName, startInfo.Arguments);
1971  Microsoft.Win32.NativeMethods.STARTUPINFO sTARTUPINFO = new Microsoft.Win32.NativeMethods.STARTUPINFO();
1972  Microsoft.Win32.SafeNativeMethods.PROCESS_INFORMATION pROCESS_INFORMATION = new Microsoft.Win32.SafeNativeMethods.PROCESS_INFORMATION();
1973  SafeProcessHandle safeProcessHandle = new SafeProcessHandle();
1974  Microsoft.Win32.SafeHandles.SafeThreadHandle safeThreadHandle = new Microsoft.Win32.SafeHandles.SafeThreadHandle();
1975  int num = 0;
1976  SafeFileHandle parentHandle = null;
1977  SafeFileHandle parentHandle2 = null;
1978  SafeFileHandle parentHandle3 = null;
1979  GCHandle gCHandle = default(GCHandle);
1980  lock (s_CreateProcessLock)
1981  {
1982  try
1983  {
1984  if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)
1985  {
1986  if (startInfo.RedirectStandardInput)
1987  {
1988  CreatePipe(out parentHandle, out sTARTUPINFO.hStdInput, parentInputs: true);
1989  }
1990  else
1991  {
1992  sTARTUPINFO.hStdInput = new SafeFileHandle(Microsoft.Win32.NativeMethods.GetStdHandle(-10), ownsHandle: false);
1993  }
1994  if (startInfo.RedirectStandardOutput)
1995  {
1996  CreatePipe(out parentHandle2, out sTARTUPINFO.hStdOutput, parentInputs: false);
1997  }
1998  else
1999  {
2000  sTARTUPINFO.hStdOutput = new SafeFileHandle(Microsoft.Win32.NativeMethods.GetStdHandle(-11), ownsHandle: false);
2001  }
2002  if (startInfo.RedirectStandardError)
2003  {
2004  CreatePipe(out parentHandle3, out sTARTUPINFO.hStdError, parentInputs: false);
2005  }
2006  else
2007  {
2008  sTARTUPINFO.hStdError = new SafeFileHandle(Microsoft.Win32.NativeMethods.GetStdHandle(-12), ownsHandle: false);
2009  }
2010  sTARTUPINFO.dwFlags = 256;
2011  }
2012  int num2 = 0;
2013  if (startInfo.CreateNoWindow)
2014  {
2015  num2 |= 0x8000000;
2016  }
2017  IntPtr intPtr = (IntPtr)0;
2018  if (startInfo.environmentVariables != null)
2019  {
2020  bool unicode = false;
2021  if (ProcessManager.IsNt)
2022  {
2023  num2 |= 0x400;
2024  unicode = true;
2025  }
2026  byte[] value = EnvironmentBlock.ToByteArray(startInfo.environmentVariables, unicode);
2027  gCHandle = GCHandle.Alloc(value, GCHandleType.Pinned);
2028  intPtr = gCHandle.AddrOfPinnedObject();
2029  }
2030  string text = startInfo.WorkingDirectory;
2031  if (text == string.Empty)
2032  {
2033  text = Environment.CurrentDirectory;
2034  }
2035  if (startInfo.UserName.Length != 0)
2036  {
2037  if (startInfo.Password != null && startInfo.PasswordInClearText != null)
2038  {
2039  throw new ArgumentException(SR.GetString("CantSetDuplicatePassword"));
2040  }
2041  Microsoft.Win32.NativeMethods.LogonFlags logonFlags = (Microsoft.Win32.NativeMethods.LogonFlags)0;
2042  if (startInfo.LoadUserProfile)
2043  {
2044  logonFlags = Microsoft.Win32.NativeMethods.LogonFlags.LOGON_WITH_PROFILE;
2045  }
2046  IntPtr intPtr2 = IntPtr.Zero;
2047  try
2048  {
2049  intPtr2 = ((startInfo.Password != null) ? Marshal.SecureStringToCoTaskMemUnicode(startInfo.Password) : ((startInfo.PasswordInClearText == null) ? Marshal.StringToCoTaskMemUni(string.Empty) : Marshal.StringToCoTaskMemUni(startInfo.PasswordInClearText)));
2051  bool flag;
2052  try
2053  {
2054  }
2055  finally
2056  {
2057  flag = Microsoft.Win32.NativeMethods.CreateProcessWithLogonW(startInfo.UserName, startInfo.Domain, intPtr2, logonFlags, null, stringBuilder, num2, intPtr, text, sTARTUPINFO, pROCESS_INFORMATION);
2058  if (!flag)
2059  {
2060  num = Marshal.GetLastWin32Error();
2061  }
2062  if (pROCESS_INFORMATION.hProcess != (IntPtr)0 && pROCESS_INFORMATION.hProcess != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)
2063  {
2064  safeProcessHandle.InitialSetHandle(pROCESS_INFORMATION.hProcess);
2065  }
2066  if (pROCESS_INFORMATION.hThread != (IntPtr)0 && pROCESS_INFORMATION.hThread != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)
2067  {
2068  safeThreadHandle.InitialSetHandle(pROCESS_INFORMATION.hThread);
2069  }
2070  }
2071  if (!flag)
2072  {
2073  if (num == 193 || num == 216)
2074  {
2075  throw new Win32Exception(num, SR.GetString("InvalidApplication"));
2076  }
2077  throw new Win32Exception(num);
2078  }
2079  }
2080  finally
2081  {
2082  if (intPtr2 != IntPtr.Zero)
2083  {
2085  }
2086  }
2087  }
2088  else
2089  {
2091  bool flag;
2092  try
2093  {
2094  }
2095  finally
2096  {
2097  flag = Microsoft.Win32.NativeMethods.CreateProcess(null, stringBuilder, null, null, bInheritHandles: true, num2, intPtr, text, sTARTUPINFO, pROCESS_INFORMATION);
2098  if (!flag)
2099  {
2100  num = Marshal.GetLastWin32Error();
2101  }
2102  if (pROCESS_INFORMATION.hProcess != (IntPtr)0 && pROCESS_INFORMATION.hProcess != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)
2103  {
2104  safeProcessHandle.InitialSetHandle(pROCESS_INFORMATION.hProcess);
2105  }
2106  if (pROCESS_INFORMATION.hThread != (IntPtr)0 && pROCESS_INFORMATION.hThread != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)
2107  {
2108  safeThreadHandle.InitialSetHandle(pROCESS_INFORMATION.hThread);
2109  }
2110  }
2111  if (!flag)
2112  {
2113  if (num == 193 || num == 216)
2114  {
2115  throw new Win32Exception(num, SR.GetString("InvalidApplication"));
2116  }
2117  throw new Win32Exception(num);
2118  }
2119  }
2120  }
2121  finally
2122  {
2123  if (gCHandle.IsAllocated)
2124  {
2125  gCHandle.Free();
2126  }
2127  sTARTUPINFO.Dispose();
2128  }
2129  }
2130  if (startInfo.RedirectStandardInput)
2131  {
2132  standardInput = new StreamWriter(new FileStream(parentHandle, FileAccess.Write, 4096, isAsync: false), Console.InputEncoding, 4096);
2133  standardInput.AutoFlush = true;
2134  }
2135  if (startInfo.RedirectStandardOutput)
2136  {
2137  Encoding encoding = (startInfo.StandardOutputEncoding != null) ? startInfo.StandardOutputEncoding : Console.OutputEncoding;
2138  standardOutput = new StreamReader(new FileStream(parentHandle2, FileAccess.Read, 4096, isAsync: false), encoding, detectEncodingFromByteOrderMarks: true, 4096);
2139  }
2140  if (startInfo.RedirectStandardError)
2141  {
2142  Encoding encoding2 = (startInfo.StandardErrorEncoding != null) ? startInfo.StandardErrorEncoding : Console.OutputEncoding;
2143  standardError = new StreamReader(new FileStream(parentHandle3, FileAccess.Read, 4096, isAsync: false), encoding2, detectEncodingFromByteOrderMarks: true, 4096);
2144  }
2145  bool result = false;
2146  if (!safeProcessHandle.IsInvalid)
2147  {
2148  SetProcessHandle(safeProcessHandle);
2149  SetProcessId(pROCESS_INFORMATION.dwProcessId);
2150  safeThreadHandle.Close();
2151  result = true;
2152  }
2153  return result;
2154  }
2155 
2156  private bool StartWithShellExecuteEx(ProcessStartInfo startInfo)
2157  {
2158  if (disposed)
2159  {
2160  throw new ObjectDisposedException(GetType().Name);
2161  }
2162  if (!string.IsNullOrEmpty(startInfo.UserName) || startInfo.Password != null)
2163  {
2164  throw new InvalidOperationException(SR.GetString("CantStartAsUser"));
2165  }
2166  if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)
2167  {
2168  throw new InvalidOperationException(SR.GetString("CantRedirectStreams"));
2169  }
2170  if (startInfo.StandardErrorEncoding != null)
2171  {
2172  throw new InvalidOperationException(SR.GetString("StandardErrorEncodingNotAllowed"));
2173  }
2174  if (startInfo.StandardOutputEncoding != null)
2175  {
2176  throw new InvalidOperationException(SR.GetString("StandardOutputEncodingNotAllowed"));
2177  }
2178  if (startInfo.environmentVariables != null)
2179  {
2180  throw new InvalidOperationException(SR.GetString("CantUseEnvVars"));
2181  }
2182  Microsoft.Win32.NativeMethods.ShellExecuteInfo shellExecuteInfo = new Microsoft.Win32.NativeMethods.ShellExecuteInfo();
2183  shellExecuteInfo.fMask = 64;
2184  if (startInfo.ErrorDialog)
2185  {
2186  shellExecuteInfo.hwnd = startInfo.ErrorDialogParentHandle;
2187  }
2188  else
2189  {
2190  shellExecuteInfo.fMask |= 1024;
2191  }
2192  switch (startInfo.WindowStyle)
2193  {
2194  case ProcessWindowStyle.Hidden:
2195  shellExecuteInfo.nShow = 0;
2196  break;
2197  case ProcessWindowStyle.Minimized:
2198  shellExecuteInfo.nShow = 2;
2199  break;
2200  case ProcessWindowStyle.Maximized:
2201  shellExecuteInfo.nShow = 3;
2202  break;
2203  default:
2204  shellExecuteInfo.nShow = 1;
2205  break;
2206  }
2207  try
2208  {
2209  if (startInfo.FileName.Length != 0)
2210  {
2211  shellExecuteInfo.lpFile = Marshal.StringToHGlobalAuto(startInfo.FileName);
2212  }
2213  if (startInfo.Verb.Length != 0)
2214  {
2215  shellExecuteInfo.lpVerb = Marshal.StringToHGlobalAuto(startInfo.Verb);
2216  }
2217  if (startInfo.Arguments.Length != 0)
2218  {
2219  shellExecuteInfo.lpParameters = Marshal.StringToHGlobalAuto(startInfo.Arguments);
2220  }
2221  if (startInfo.WorkingDirectory.Length != 0)
2222  {
2223  shellExecuteInfo.lpDirectory = Marshal.StringToHGlobalAuto(startInfo.WorkingDirectory);
2224  }
2225  shellExecuteInfo.fMask |= 256;
2226  ShellExecuteHelper shellExecuteHelper = new ShellExecuteHelper(shellExecuteInfo);
2227  int num;
2228  if (!shellExecuteHelper.ShellExecuteOnSTAThread())
2229  {
2230  num = shellExecuteHelper.ErrorCode;
2231  if (num == 0)
2232  {
2233  long num2 = (long)shellExecuteInfo.hInstApp;
2234  long num3 = num2 - 2;
2235  if ((ulong)num3 <= 6uL)
2236  {
2237  switch (num3)
2238  {
2239  case 0L:
2240  goto IL_023b;
2241  case 1L:
2242  goto IL_023f;
2243  case 3L:
2244  goto IL_0243;
2245  case 6L:
2246  goto IL_0247;
2247  case 2L:
2248  case 4L:
2249  case 5L:
2250  goto IL_0268;
2251  }
2252  }
2253  long num4 = num2 - 26;
2254  if ((ulong)num4 > 6uL)
2255  {
2256  goto IL_0268;
2257  }
2258  switch (num4)
2259  {
2260  case 2L:
2261  case 3L:
2262  case 4L:
2263  break;
2264  case 0L:
2265  goto IL_0253;
2266  case 5L:
2267  goto IL_0258;
2268  case 6L:
2269  goto IL_0260;
2270  default:
2271  goto IL_0268;
2272  }
2273  num = 1156;
2274  }
2275  goto IL_0274;
2276  }
2277  goto end_IL_0124;
2278  IL_023f:
2279  num = 3;
2280  goto IL_0274;
2281  IL_0243:
2282  num = 5;
2283  goto IL_0274;
2284  IL_023b:
2285  num = 2;
2286  goto IL_0274;
2287  IL_0268:
2288  num = (int)shellExecuteInfo.hInstApp;
2289  goto IL_0274;
2290  IL_0258:
2291  num = 1155;
2292  goto IL_0274;
2293  IL_0260:
2294  num = 1157;
2295  goto IL_0274;
2296  IL_0253:
2297  num = 32;
2298  goto IL_0274;
2299  IL_0274:
2300  if (num == 193 || num == 216)
2301  {
2302  throw new Win32Exception(num, SR.GetString("InvalidApplication"));
2303  }
2304  throw new Win32Exception(num);
2305  IL_0247:
2306  num = 8;
2307  goto IL_0274;
2308  end_IL_0124:;
2309  }
2310  finally
2311  {
2312  if (shellExecuteInfo.lpFile != (IntPtr)0)
2313  {
2314  Marshal.FreeHGlobal(shellExecuteInfo.lpFile);
2315  }
2316  if (shellExecuteInfo.lpVerb != (IntPtr)0)
2317  {
2318  Marshal.FreeHGlobal(shellExecuteInfo.lpVerb);
2319  }
2320  if (shellExecuteInfo.lpParameters != (IntPtr)0)
2321  {
2322  Marshal.FreeHGlobal(shellExecuteInfo.lpParameters);
2323  }
2324  if (shellExecuteInfo.lpDirectory != (IntPtr)0)
2325  {
2326  Marshal.FreeHGlobal(shellExecuteInfo.lpDirectory);
2327  }
2328  }
2329  if (shellExecuteInfo.hProcess != (IntPtr)0)
2330  {
2331  SafeProcessHandle processHandle = new SafeProcessHandle(shellExecuteInfo.hProcess);
2332  SetProcessHandle(processHandle);
2333  return true;
2334  }
2335  return false;
2336  }
2337 
2349  public static Process Start(string fileName, string userName, SecureString password, string domain)
2350  {
2351  ProcessStartInfo processStartInfo = new ProcessStartInfo(fileName);
2352  processStartInfo.UserName = userName;
2353  processStartInfo.Password = password;
2354  processStartInfo.Domain = domain;
2355  processStartInfo.UseShellExecute = false;
2356  return Start(processStartInfo);
2357  }
2358 
2371  public static Process Start(string fileName, string arguments, string userName, SecureString password, string domain)
2372  {
2373  ProcessStartInfo processStartInfo = new ProcessStartInfo(fileName, arguments);
2374  processStartInfo.UserName = userName;
2375  processStartInfo.Password = password;
2376  processStartInfo.Domain = domain;
2377  processStartInfo.UseShellExecute = false;
2378  return Start(processStartInfo);
2379  }
2380 
2387  public static Process Start(string fileName)
2388  {
2389  return Start(new ProcessStartInfo(fileName));
2390  }
2391 
2400  public static Process Start(string fileName, string arguments)
2401  {
2402  return Start(new ProcessStartInfo(fileName, arguments));
2403  }
2404 
2413  public static Process Start(ProcessStartInfo startInfo)
2414  {
2415  Process process = new Process();
2416  if (startInfo == null)
2417  {
2418  throw new ArgumentNullException("startInfo");
2419  }
2420  process.StartInfo = startInfo;
2421  if (process.Start())
2422  {
2423  return process;
2424  }
2425  return null;
2426  }
2427 
2432  public void Kill()
2433  {
2434  SafeProcessHandle safeProcessHandle = null;
2435  try
2436  {
2437  safeProcessHandle = GetProcessHandle(1);
2438  if (!Microsoft.Win32.NativeMethods.TerminateProcess(safeProcessHandle, -1))
2439  {
2440  throw new Win32Exception();
2441  }
2442  }
2443  finally
2444  {
2445  ReleaseProcessHandle(safeProcessHandle);
2446  }
2447  }
2448 
2449  private void StopWatchingForExit()
2450  {
2451  if (watchingForExit)
2452  {
2453  lock (this)
2454  {
2455  if (watchingForExit)
2456  {
2457  watchingForExit = false;
2458  registeredWaitHandle.Unregister(null);
2459  waitHandle.Close();
2460  waitHandle = null;
2461  registeredWaitHandle = null;
2462  }
2463  }
2464  }
2465  }
2466 
2471  public override string ToString()
2472  {
2473  if (Associated)
2474  {
2475  string text = string.Empty;
2476  try
2477  {
2478  text = ProcessName;
2479  }
2481  {
2482  }
2483  if (text.Length != 0)
2484  {
2485  return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", new object[2]
2486  {
2487  base.ToString(),
2488  text
2489  });
2490  }
2491  return base.ToString();
2492  }
2493  return base.ToString();
2494  }
2495 
2502  public bool WaitForExit(int milliseconds)
2503  {
2504  SafeProcessHandle safeProcessHandle = null;
2505  ProcessWaitHandle processWaitHandle = null;
2506  bool flag;
2507  try
2508  {
2509  safeProcessHandle = GetProcessHandle(1048576, throwIfExited: false);
2510  if (safeProcessHandle.IsInvalid)
2511  {
2512  flag = true;
2513  }
2514  else
2515  {
2516  processWaitHandle = new ProcessWaitHandle(safeProcessHandle);
2517  if (processWaitHandle.WaitOne(milliseconds, exitContext: false))
2518  {
2519  flag = true;
2520  signaled = true;
2521  }
2522  else
2523  {
2524  flag = false;
2525  signaled = false;
2526  }
2527  }
2528  }
2529  finally
2530  {
2531  processWaitHandle?.Close();
2532  if (output != null && milliseconds == -1)
2533  {
2534  output.WaitUtilEOF();
2535  }
2536  if (error != null && milliseconds == -1)
2537  {
2538  error.WaitUtilEOF();
2539  }
2540  ReleaseProcessHandle(safeProcessHandle);
2541  }
2542  if (flag && watchForExit)
2543  {
2544  RaiseOnExited();
2545  }
2546  return flag;
2547  }
2548 
2552  public void WaitForExit()
2553  {
2554  WaitForExit(-1);
2555  }
2556 
2562  public bool WaitForInputIdle(int milliseconds)
2563  {
2564  SafeProcessHandle handle = null;
2565  try
2566  {
2567  handle = GetProcessHandle(1049600);
2568  switch (Microsoft.Win32.NativeMethods.WaitForInputIdle(handle, milliseconds))
2569  {
2570  case 0:
2571  return true;
2572  case 258:
2573  return false;
2574  default:
2575  throw new InvalidOperationException(SR.GetString("InputIdleUnkownError"));
2576  }
2577  }
2578  finally
2579  {
2580  ReleaseProcessHandle(handle);
2581  }
2582  }
2583 
2588  public bool WaitForInputIdle()
2589  {
2590  return WaitForInputIdle(int.MaxValue);
2591  }
2592 
2595  [ComVisible(false)]
2596  public void BeginOutputReadLine()
2597  {
2598  if (outputStreamReadMode == StreamReadMode.undefined)
2599  {
2600  outputStreamReadMode = StreamReadMode.asyncMode;
2601  }
2602  else if (outputStreamReadMode != StreamReadMode.asyncMode)
2603  {
2604  throw new InvalidOperationException(SR.GetString("CantMixSyncAsyncOperation"));
2605  }
2606  if (pendingOutputRead)
2607  {
2608  throw new InvalidOperationException(SR.GetString("PendingAsyncOperation"));
2609  }
2610  pendingOutputRead = true;
2611  if (output == null)
2612  {
2613  if (standardOutput == null)
2614  {
2615  throw new InvalidOperationException(SR.GetString("CantGetStandardOut"));
2616  }
2617  Stream baseStream = standardOutput.BaseStream;
2618  output = new AsyncStreamReader(this, baseStream, OutputReadNotifyUser, standardOutput.CurrentEncoding);
2619  }
2620  output.BeginReadLine();
2621  }
2622 
2625  [ComVisible(false)]
2626  public void BeginErrorReadLine()
2627  {
2628  if (errorStreamReadMode == StreamReadMode.undefined)
2629  {
2630  errorStreamReadMode = StreamReadMode.asyncMode;
2631  }
2632  else if (errorStreamReadMode != StreamReadMode.asyncMode)
2633  {
2634  throw new InvalidOperationException(SR.GetString("CantMixSyncAsyncOperation"));
2635  }
2636  if (pendingErrorRead)
2637  {
2638  throw new InvalidOperationException(SR.GetString("PendingAsyncOperation"));
2639  }
2640  pendingErrorRead = true;
2641  if (error == null)
2642  {
2643  if (standardError == null)
2644  {
2645  throw new InvalidOperationException(SR.GetString("CantGetStandardError"));
2646  }
2647  Stream baseStream = standardError.BaseStream;
2648  error = new AsyncStreamReader(this, baseStream, ErrorReadNotifyUser, standardError.CurrentEncoding);
2649  }
2650  error.BeginReadLine();
2651  }
2652 
2655  [ComVisible(false)]
2656  public void CancelOutputRead()
2657  {
2658  if (output != null)
2659  {
2660  output.CancelOperation();
2661  pendingOutputRead = false;
2662  return;
2663  }
2664  throw new InvalidOperationException(SR.GetString("NoAsyncOperation"));
2665  }
2666 
2669  [ComVisible(false)]
2670  public void CancelErrorRead()
2671  {
2672  if (error != null)
2673  {
2674  error.CancelOperation();
2675  pendingErrorRead = false;
2676  return;
2677  }
2678  throw new InvalidOperationException(SR.GetString("NoAsyncOperation"));
2679  }
2680 
2681  internal void OutputReadNotifyUser(string data)
2682  {
2683  DataReceivedEventHandler outputDataReceived = this.OutputDataReceived;
2684  if (outputDataReceived != null)
2685  {
2686  DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data);
2688  {
2689  SynchronizingObject.Invoke(outputDataReceived, new object[2]
2690  {
2691  this,
2692  dataReceivedEventArgs
2693  });
2694  }
2695  else
2696  {
2697  outputDataReceived(this, dataReceivedEventArgs);
2698  }
2699  }
2700  }
2701 
2702  internal void ErrorReadNotifyUser(string data)
2703  {
2704  DataReceivedEventHandler errorDataReceived = this.ErrorDataReceived;
2705  if (errorDataReceived != null)
2706  {
2707  DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data);
2709  {
2710  SynchronizingObject.Invoke(errorDataReceived, new object[2]
2711  {
2712  this,
2713  dataReceivedEventArgs
2714  });
2715  }
2716  else
2717  {
2718  errorDataReceived(this, dataReceivedEventArgs);
2719  }
2720  }
2721  }
2722  }
2723 }
Represents a character encoding.To browse the .NET Framework source code for this type,...
Definition: Encoding.cs:15
static void EnterDebugMode()
Puts a T:System.Diagnostics.Process component in state to interact with operating system processes th...
Definition: Process.cs:1552
ProcessModule MainModule
Gets the main module for the associated process.
Definition: Process.cs:425
static Process Start(string fileName, string userName, SecureString password, string domain)
Starts a process resource by specifying the name of an application, a user name, a password,...
Definition: Process.cs:2349
bool EnableRaisingEvents
Gets or sets whether the E:System.Diagnostics.Process.Exited event should be raised when the process ...
Definition: Process.cs:1166
DateTime StartTime
Gets the time that the associated process was started.
Definition: Process.cs:1036
PlatformID
Identifies the operating system, or platform, supported by an assembly.
Definition: PlatformID.cs:8
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
static Process Start(string fileName)
Starts a process resource by specifying the name of a document or application file and associates the...
Definition: Process.cs:2387
static Process Start(string fileName, string arguments, string userName, SecureString password, string domain)
Starts a process resource by specifying the name of an application, a set of command-line arguments,...
Definition: Process.cs:2371
TimeSpan UserProcessorTime
Gets the user processor time for this process.
Definition: Process.cs:1121
int ExitCode
Gets the value that the associated process specified when it terminated.
Definition: Process.cs:186
DataReceivedEventHandler ErrorDataReceived
Occurs when an application writes to its redirected P:System.Diagnostics.Process.StandardError stream...
Definition: Process.cs:1301
IComponent RootComponent
Gets the instance of the base class used as the root component for the current design.
Encapsulates operating system–specific objects that wait for exclusive access to shared resources.
Definition: WaitHandle.cs:15
Represents a handle that has been registered when calling M:System.Threading.ThreadPool....
static void FreeHGlobal(IntPtr hglobal)
Frees memory previously allocated from the unmanaged memory of the process.
Definition: Marshal.cs:1458
unsafe override string ToString()
Converts the value of this instance to a T:System.String.
Represents an operating system process thread.
void Refresh()
Discards any information about the associated process that has been cached inside the process compone...
Definition: Process.cs:1798
long VirtualMemorySize64
Gets the amount of the virtual memory, in bytes, allocated for the associated process.
Definition: Process.cs:1151
Process()
Initializes a new instance of the T:System.Diagnostics.Process class.
Definition: Process.cs:1319
static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
Copies the contents of a managed T:System.Security.SecureString object to a block of memory allocated...
Definition: Marshal.cs:2927
static Process [] GetProcessesByName(string processName)
Creates an array of new T:System.Diagnostics.Process components and associates them with all the proc...
Definition: Process.cs:1629
int HandleCount
Gets the number of handles opened by the process.
Definition: Process.cs:319
StringComparison
Specifies the culture, case, and sort rules to be used by certain overloads of the M:System....
Provides a strongly typed collection of T:System.Diagnostics.ProcessThread objects.
bool WaitForInputIdle()
Causes the T:System.Diagnostics.Process component to wait indefinitely for the associated process to ...
Definition: Process.cs:2588
string MainWindowTitle
Gets the caption of the main window of the process.
Definition: Process.cs:393
void WaitForExit()
Instructs the T:System.Diagnostics.Process component to wait indefinitely for the associated process ...
Definition: Process.cs:2552
long PeakWorkingSet64
Gets the maximum amount of physical memory, in bytes, used by the associated process.
Definition: Process.cs:661
string MachineName
Gets the name of the computer the associated process is running on.
Definition: Process.cs:349
long PeakVirtualMemorySize64
Gets the maximum amount of virtual memory, in bytes, used by the associated process.
Definition: Process.cs:691
virtual int Count
Gets the number of elements actually contained in the T:System.Collections.ArrayList.
Definition: ArrayList.cs:2255
Definition: __Canon.cs:3
ProcessThreadCollection Threads
Gets the set of threads that are running in the associated process.
Definition: Process.cs:1081
static OperatingSystem OSVersion
Gets an T:System.OperatingSystem object that contains the current platform identifier and version num...
Definition: Environment.cs:477
bool UseShellExecute
Gets or sets a value indicating whether to use the operating system shell to start the process.
Wraps a managed object holding a handle to a resource that is passed to unmanaged code using platform...
Definition: HandleRef.cs:5
Implements a T:System.IO.TextReader that reads characters from a byte stream in a particular encoding...
Definition: StreamReader.cs:13
static void LeaveDebugMode()
Takes a T:System.Diagnostics.Process component out of the state that lets it interact with operating ...
Definition: Process.cs:1591
Represents an instant in time, typically expressed as a date and time of day. To browse the ....
Definition: DateTime.cs:13
Provides a way to synchronously or asynchronously execute a delegate.
void BeginOutputReadLine()
Begins asynchronous read operations on the redirected P:System.Diagnostics.Process....
Definition: Process.cs:2596
static string GetFileName(string path)
Returns the file name and extension of the specified path string.
Definition: Path.cs:914
Represents the base class for classes that contain event data, and provides a value to use for events...
Definition: EventArgs.cs:9
DateTime ExitTime
Gets the time that the associated process exited.
Definition: Process.cs:271
Provides a strongly typed collection of T:System.Diagnostics.ProcessModule objects.
static Delegate Remove(Delegate source, Delegate value)
Removes the last occurrence of the invocation list of a delegate from the invocation list of another ...
Definition: Delegate.cs:287
DataReceivedEventHandler OutputDataReceived
Occurs each time an application writes a line to its redirected P:System.Diagnostics....
Definition: Process.cs:1296
static Delegate Combine(Delegate a, Delegate b)
Concatenates the invocation lists of two delegates.
Definition: Delegate.cs:202
static Process [] GetProcesses(string machineName)
Creates a new T:System.Diagnostics.Process component for each process resource on the specified compu...
Definition: Process.cs:1682
Version Version
Gets a T:System.Version object that identifies the operating system.
StreamReader StandardError
Gets a stream used to read the error output of the application.
Definition: Process.cs:1244
ProcessWindowStyle
Specified how a new window should appear when the system starts a process.
ProcessStartInfo StartInfo
Gets or sets the properties to pass to the M:System.Diagnostics.Process.Start method of the T:System....
Definition: Process.cs:1008
Represents a wrapper class for operating system handles. This class must be inherited.
Definition: SafeHandle.cs:12
Specifies a set of values that are used when you start a process.
bool InvokeRequired
Gets a value indicating whether the caller must call M:System.ComponentModel.ISynchronizeInvoke....
long PagedSystemMemorySize64
Gets the amount of pageable system memory, in bytes, allocated for the associated process.
Definition: Process.cs:601
PlatformID Platform
Gets a T:System.PlatformID enumeration value that identifies the operating system platform.
int PagedMemorySize
Gets the amount of paged memory, in bytes, allocated for the associated process.
Definition: Process.cs:556
Represents a.dll or .exe file that is loaded into a particular process.
int PeakVirtualMemorySize
Gets the maximum amount of virtual memory, in bytes, used by the associated process.
Definition: Process.cs:676
int NonpagedSystemMemorySize
Gets the amount of nonpaged system memory, in bytes, allocated for the associated process.
Definition: Process.cs:526
bool IsAllocated
Gets a value indicating whether the handle is allocated.
Definition: GCHandle.cs:53
The exception thrown when using invalid arguments that are enumerators.
SecurityAction
Specifies the security actions that can be performed using declarative security.
Implements a T:System.IO.TextWriter for writing characters to a stream in a particular encoding....
Definition: StreamWriter.cs:15
IntPtr MaxWorkingSet
Gets or sets the maximum allowable working set size, in bytes, for the associated process.
Definition: Process.cs:457
static Process [] GetProcessesByName(string processName, string machineName)
Creates an array of new T:System.Diagnostics.Process components and associates them with all the proc...
Definition: Process.cs:1643
Provides information about, and means to manipulate, the current environment and platform....
Definition: Environment.cs:21
static bool IsDefined(Type enumType, object value)
Returns an indication whether a constant with a specified value exists in a specified enumeration.
Definition: Enum.cs:577
IntPtr MinWorkingSet
Gets or sets the minimum allowable working set size, in bytes, for the associated process.
Definition: Process.cs:479
delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e)
Represents the method that will handle the E:System.Diagnostics.Process.OutputDataReceived event or E...
static readonly EventArgs Empty
Provides a value to use with events that do not have event data.
Definition: EventArgs.cs:13
ISynchronizeInvoke SynchronizingObject
Gets or sets the object used to marshal the event handler calls that are issued as a result of a proc...
Definition: Process.cs:1050
EventHandler Exited
Occurs when a process exits.
Definition: Process.cs:1307
StringBuilder Append(char value, int repeatCount)
Appends a specified number of copies of the string representation of a Unicode character to this inst...
bool CloseMainWindow()
Closes a process that has a user interface by sending a close message to its main window.
Definition: Process.cs:1372
static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce)
Registers a delegate to wait for a T:System.Threading.WaitHandle, specifying a 32-bit unsigned intege...
Definition: ThreadPool.cs:82
string UserName
Gets or sets the user name to be used when starting the process.
bool? HasExited
Gets a value indicating whether the associated process has been terminated.
Definition: Process.cs:204
int Major
Gets the value of the major component of the version number for the current T:System....
Definition: Version.cs:103
Represents a collection that can contain many different types of permissions.
string ProcessName
Gets the name of the process.
Definition: Process.cs:882
Throws an exception for a Win32 error code.
Provides the base class for enumerations.
Definition: Enum.cs:14
TimeSpan PrivilegedProcessorTime
Gets the privileged processor time for this process.
Definition: Process.cs:866
string ModuleName
Gets the name of the process module.
int PrivateMemorySize
Gets the amount of private memory, in bytes, allocated for the associated process.
Definition: Process.cs:836
delegate void EventHandler(object sender, EventArgs e)
Represents the method that will handle an event that has no event data.
virtual Stream BaseStream
Returns the underlying stream.
Provides a T:System.IO.Stream for a file, supporting both synchronous and asynchronous read and write...
Definition: FileStream.cs:15
StreamWriter StandardInput
Gets a stream used to write the input of the application.
Definition: Process.cs:1200
bool PriorityBoostEnabled
Gets or sets a value indicating whether the associated process priority should temporarily be boosted...
Definition: Process.cs:721
Represents text that should be kept confidential, such as by deleting it from computer memory when no...
Definition: SecureString.cs:11
string FileName
Gets or sets the application or document to start.
long PrivateMemorySize64
Gets the amount of private memory, in bytes, allocated for the associated process.
Definition: Process.cs:851
StreamReader StandardOutput
Gets a stream used to read the textual output of the application.
Definition: Process.cs:1218
The exception that is thrown when a feature does not run on a particular platform.
A platform-specific type that is used to represent a pointer or a handle.
Definition: IntPtr.cs:14
ProcessPriorityClass PriorityClass
Gets or sets the overall priority category for the associated process.
Definition: Process.cs:777
Provides access to local and remote processes and enables you to start and stop local system processe...
Definition: Process.cs:25
static void PrepareConstrainedRegions()
Designates a body of code as a constrained execution region (CER).
Provides the base implementation for the T:System.ComponentModel.IComponent interface and enables obj...
Definition: Component.cs:9
Represents a delegate, which is a data structure that refers to a static method or to a class instanc...
Definition: Delegate.cs:15
static GCHandle Alloc(object value)
Allocates a F:System.Runtime.InteropServices.GCHandleType.Normal handle for the specified object.
Definition: GCHandle.cs:98
Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks,...
Definition: Marshal.cs:15
GCHandleType
Represents the types of handles the T:System.Runtime.InteropServices.GCHandle class can allocate.
Definition: GCHandleType.cs:7
override string ToString()
Formats the process's name as a string, combined with the parent component type, if applicable.
Definition: Process.cs:2471
int VirtualMemorySize
Gets the size of the process's virtual memory, in bytes.
Definition: Process.cs:1136
Provides a way to access a managed object from unmanaged memory.
Definition: GCHandle.cs:10
IntPtr AddrOfPinnedObject()
Retrieves the address of an object in a F:System.Runtime.InteropServices.GCHandleType....
Definition: GCHandle.cs:138
long WorkingSet64
Gets the amount of physical memory, in bytes, allocated for the associated process.
Definition: Process.cs:1285
virtual void CopyTo(Array array)
Copies the entire T:System.Collections.ArrayList to a compatible one-dimensional T:System....
Definition: ArrayList.cs:2516
override void Dispose(bool disposing)
Release all resources used by this process.
Definition: Process.cs:1405
static Process GetProcessById(int processId)
Returns a new T:System.Diagnostics.Process component, given the identifier of a process on the local ...
Definition: Process.cs:1620
Provides data for the E:System.Diagnostics.Process.OutputDataReceived and E:System....
static unsafe IntPtr StringToCoTaskMemUni(string s)
Copies the contents of a managed T:System.String to a block of memory allocated from the unmanaged CO...
Definition: Marshal.cs:2084
virtual void Close()
Releases all resources held by the current T:System.Threading.WaitHandle.
Definition: WaitHandle.cs:714
int BasePriority
Gets the base priority of the associated process.
Definition: Process.cs:170
int PagedSystemMemorySize
Gets the amount of pageable system memory, in bytes, allocated for the associated process.
Definition: Process.cs:586
Provides a multilevel switch to control tracing and debug output without recompiling your code.
Definition: TraceSwitch.cs:8
virtual bool AutoFlush
Gets or sets a value indicating whether the T:System.IO.StreamWriter will flush its buffer to the und...
void Kill()
Immediately stops the associated process.
Definition: Process.cs:2432
Represents a mutable string of characters. This class cannot be inherited.To browse the ....
virtual int Add(object value)
Adds an object to the end of the T:System.Collections.ArrayList.
Definition: ArrayList.cs:2381
IntPtr ProcessorAffinity
Gets or sets the processors on which the threads in this process can be scheduled to run.
Definition: Process.cs:914
int WorkingSet
Gets the associated process's physical memory usage, in bytes.
Definition: Process.cs:1270
virtual object GetService(Type service)
Returns an object that represents a service provided by the T:System.ComponentModel....
Definition: Component.cs:131
Represents information about an operating system, such as the version and platform identifier....
int PeakPagedMemorySize
Gets the maximum amount of memory in the virtual memory paging file, in bytes, used by the associated...
Definition: Process.cs:616
bool WaitForInputIdle(int milliseconds)
Causes the T:System.Diagnostics.Process component to wait the specified number of milliseconds for th...
Definition: Process.cs:2562
void OnExited()
Raises the E:System.Diagnostics.Process.Exited event.
Definition: Process.cs:1703
void Close()
Frees all the resources that are associated with this component.
Definition: Process.cs:1419
static CultureInfo CurrentCulture
Gets or sets the T:System.Globalization.CultureInfo object that represents the culture used by the cu...
Definition: CultureInfo.cs:120
The exception that is thrown when one of the arguments provided to a method is not valid.
void Free()
Releases a T:System.Runtime.InteropServices.GCHandle.
Definition: GCHandle.cs:119
void CancelErrorRead()
Cancels the asynchronous read operation on the redirected P:System.Diagnostics.Process....
Definition: Process.cs:2670
long PagedMemorySize64
Gets the amount of paged memory, in bytes, allocated for the associated process.
Definition: Process.cs:571
SecureString Password
Gets or sets a secure string that contains the user password to use when starting the process.
int Capacity
Gets or sets the maximum number of characters that can be contained in the memory allocated by the cu...
static void ZeroFreeCoTaskMemUnicode(IntPtr s)
Frees an unmanaged string pointer that was allocated using the M:System.Runtime.InteropServices....
Definition: Marshal.cs:2957
TimeSpan TotalProcessorTime
Gets the total processor time for this process.
Definition: Process.cs:1106
int Id
Gets the unique identifier for the associated process.
Definition: Process.cs:334
static Process GetProcessById(int processId, string machineName)
Returns a new T:System.Diagnostics.Process component, given a process identifier and the name of a co...
Definition: Process.cs:1606
Represents errors that occur during application execution.To browse the .NET Framework source code fo...
Definition: Exception.cs:22
DesignerSerializationVisibility
Specifies the visibility a property has to the design-time serializer.
FileAccess
Defines constants for read, write, or read/write access to a file.
Definition: FileAccess.cs:9
static readonly IntPtr Zero
A read-only field that represents a pointer or handle that has been initialized to zero.
Definition: IntPtr.cs:20
static Process Start(string fileName, string arguments)
Starts a process resource by specifying the name of an application and a set of command-line argument...
Definition: Process.cs:2400
virtual Encoding CurrentEncoding
Gets the current character encoding that the current T:System.IO.StreamReader object is using.
Represents a time interval.To browse the .NET Framework source code for this type,...
Definition: TimeSpan.cs:12
IntPtr MainWindowHandle
Gets the window handle of the main window of the associated process.
Definition: Process.cs:365
Provides an interface for managing designer transactions and components.
Definition: IDesignerHost.cs:7
static IntPtr StringToHGlobalAuto(string s)
Copies the contents of a managed T:System.String into unmanaged memory, converting into ANSI format i...
Definition: Marshal.cs:1544
static Process Start(ProcessStartInfo startInfo)
Starts the process resource that is specified by the parameter containing process start information (...
Definition: Process.cs:2413
The exception that is thrown when a method call is invalid for the object's current state.
int PeakWorkingSet
Gets the peak working set size for the associated process, in bytes.
Definition: Process.cs:646
IAsyncResult BeginInvoke(Delegate method, object[] args)
Asynchronously executes the delegate on the thread that created this object.
bool Start()
Starts (or reuses) the process resource that is specified by the P:System.Diagnostics....
Definition: Process.cs:1882
static Process GetCurrentProcess()
Gets a new T:System.Diagnostics.Process component and associates it with the currently active process...
Definition: Process.cs:1697
long NonpagedSystemMemorySize64
Gets the amount of nonpaged system memory, in bytes, allocated for the associated process.
Definition: Process.cs:541
void BeginErrorReadLine()
Begins asynchronous read operations on the redirected P:System.Diagnostics.Process....
Definition: Process.cs:2626
object Invoke(Delegate method, object[] args)
Synchronously executes the delegate on the thread that created this object and marshals the call to t...
Provides information about a specific culture (called a locale for unmanaged code development)....
Definition: CultureInfo.cs:16
ProcessModuleCollection Modules
Gets the modules that have been loaded by the associated process.
Definition: Process.cs:501
int SessionId
Gets the Terminal Services session identifier for the associated process.
Definition: Process.cs:993
IntPtr Handle
Gets the native handle of the associated process.
Definition: Process.cs:292
static int GetLastWin32Error()
Returns the error code returned by the last unmanaged function that was called using platform invoke ...
string Domain
Gets or sets a value that identifies the domain to use when starting the process.
bool Responding
Gets a value indicating whether the user interface of the process is responding.
Definition: Process.cs:966
long PeakPagedMemorySize64
Gets the maximum amount of memory in the virtual memory paging file, in bytes, used by the associated...
Definition: Process.cs:631
static Process [] GetProcesses()
Creates a new T:System.Diagnostics.Process component for each process resource on the local computer.
Definition: Process.cs:1669
Performs operations on T:System.String instances that contain file or directory path information....
Definition: Path.cs:13
bool WaitForExit(int milliseconds)
Instructs the T:System.Diagnostics.Process component to wait the specified number of milliseconds for...
Definition: Process.cs:2502
void CancelOutputRead()
Cancels the asynchronous read operation on the redirected P:System.Diagnostics.Process....
Definition: Process.cs:2656
ProcessPriorityClass
Indicates the priority that the system associates with a process. This value, together with the prior...
Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I...
Definition: ThreadPool.cs:14
Provides a set of static methods and properties that provide support for compilers....
bool Unregister(WaitHandle waitObject)
Cancels a registered wait operation issued by the M:System.Threading.ThreadPool.RegisterWaitForSingle...
Implements the T:System.Collections.IList interface using an array whose size is dynamically increase...
Definition: ArrayList.cs:14
Provides a generic view of a sequence of bytes. This is an abstract class.To browse the ....
Definition: Stream.cs:16
static string ChangeExtension(string path, string extension)
Changes the extension of a path string.
Definition: Path.cs:228