0

I have a problem of killing an exe with specific location that runs as administrator. Here is the code i use:

 const string PROCESSNAME = "test";
 string targetProcessPath = @Path.Combine(myFolder, "test.exe");
 Process[] collectionOfProcess = Process.GetProcessesByName(PROCESSNAME);
 if (collectionOfProcess.Length >= 1)
 {
      Process process = collectionOfProcess[0];
      string processPath = process.MainModule.FileName;
      if (processPath == targetProcessPath)
           process.Kill();
}

The problem is it works fine when i run test.exe normally but "access denied" when i run it as administrator. I have also tried to run my program as administrator but it still throws the "access denied" exception. Any help on how to achieve that?

takatto
  • 63
  • 7
  • Did you check if this is OK: `processPath == targetProcessPath` ? – Luuk Jun 06 '21 at 16:04
  • Maybe this is a better way to do that check: `String.Compare(processPath,targetProcessPath,true)==0` – Luuk Jun 06 '21 at 16:11
  • @Luuk thanks for your reply but the code you recommended still throws access denied. Only when i run the test.exe as administrator though (my program also run as administrator). – takatto Jun 06 '21 at 16:14
  • Conclusion, you are not allowed to access `process.MainModule.FileName` of the process which is running under administrator, while you yourself is not an administrator. (But `process.Kill()` still works, but then you will not know if you killed the right process.....) – Luuk Jun 06 '21 at 16:17
  • It does kill the right process, if i run two "test.exe" one is right folder and second is from another it will only kill the first one. – takatto Jun 06 '21 at 16:21
  • see this post for a possible solution: https://stackoverflow.com/questions/9501771/how-to-avoid-a-win32-exception-when-accessing-process-mainmodule-filename-in-c – Luuk Jun 06 '21 at 16:23
  • Well yeah like you said cant access process.MainModule.FileName despite running my program as administrator, that is why im asking if i have a way to achieve that. – takatto Jun 06 '21 at 16:23

0 Answers0