A lightweight alternative to Process.GetCurrentProcess().ProcessName

Unfortunately, the following (seemingly harmless code) requires administrator rights (and on Windows 2003 you will need to be member of “Performance Monitor Users” group):

System.Diagnostics.Process.GetCurrentProcess().ProcessName

In most cases this is not appropriate and certainly not in a Citrix environment. If you call it without the correct permissions you the following stack dump:

Unhandled exception in EntryPoint: System.InvalidOperationException: Couldn't get process information from remote machine. ---> System.ComponentModel.Win32Exception: Access is denied    
 at System.Diagnostics.PerformanceMonitor.GetData(String item)    
 at System.Diagnostics.PerformanceCounterLib.GetPerformanceData(String item)    
 at System.Diagnostics.PerformanceCounterLib.get_CategoryTable()    
 at System.Diagnostics.PerformanceCounterLib.GetPerformanceData(String[] categories, Int32[] categoryIndexes)    
 at System.Diagnostics.NtProcessManager.GetProcessInfos(PerformanceCounterLib library)   
  --- End of inner exception stack trace ---    
 at System.Diagnostics.NtProcessManager.GetProcessInfos(PerformanceCounterLib library)    
 at System.Diagnostics.NtProcessManager.GetProcessInfos(String machineName, Boolean isRemoteMachine)    
 at System.Diagnostics.ProcessManager.GetProcessInfos(String machineName)    
 at System.Diagnostics.Process.EnsureState(State state)    
 at System.Diagnostics.Process.get_ProcessName()    

Below is a light weight alternative to System.Diagnostics.Process.GetCurrentProcess().ProcessName and does not require any special permissions:

/// <summary>
/// Returns the starting process name (same as System.Diagnostics.Process.GetCurrentProcess().ProcessName),
/// but doesn't require any admin rights.
/// </summary>
/// <returns>Returns the starting process name.</returns>
public static string GetCurrentProcessNameLite()
{
	string procName = new System.IO.FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location).Name;
	if (procName.ToLower().IndexOf(".exe") > -1)
	{
		// Remove the ".exe" extension
		procName = procName.Substring(0, procName.Length - 4);
	}
	return procName;
}

Leave a Reply

Your email address will not be published. Required fields are marked *