I want to handle this differently, ie. determine if I have access or not.
Is it possible to see if you have access to the main module or not?
foreach (Process p in Process.GetProcesses())
{
try
{
//This throws error for some processes.
if (p.MainModule.FileName.ToLower().EndsWith(ExeName, StringComparison.CurrentCultureIgnoreCase))
{
//Do some stuff
}
}
catch (Exception)
{
//Acess denied
}
}
[Flags]
private enum ProcessAccessFlags : uint
{
QueryLimitedInformation = 0x00001000
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool QueryFullProcessImageName(
[In] IntPtr hProcess,
[In] int dwFlags,
[Out] StringBuilder lpExeName,
ref int lpdwSize);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(
ProcessAccessFlags processAccess,
bool bInheritHandle,
int processId);
String GetProcessFilename(Process p)
{
int capacity = 2000;
StringBuilder builder = new StringBuilder(capacity);
IntPtr ptr = OpenProcess(ProcessAccessFlags.QueryLimitedInformation, false, p.Id);
if (!QueryFullProcessImageName(ptr, 0, builder, ref capacity))
{
return String.Empty;
}
return builder.ToString();
}
Use pinvoke with ProcessAccessFlags.QueryLimitedInformation
. This will allow you to grab the filename of the process without having special admin privileges and works across x32 and x64 processes.
I see two possible causes of the exception:
Just use a try/catch to your loop to deal with those processes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With