2

I have an interesting problem here, as this bug only appears when there is NO Debug statements preceding the access to FileName.

//make a new process
process = new Process();
process.StartInfo.FileName = executable;
process.Start();
Debug.Print((process.MainModule == null).ToString());
Debug.Print(process.MainModule.FileName);
path = process.MainModule.FileName;
process.Kill();

I essentially just want to access the file path of the executable that I hand to it (ex: chrome.exe, so it finds the path and I can later get the icon, etc.). However, without the Debug statements, the code simply doesn't work, and spits back a NullReferenceException for

path = process.MainModule.FileName

I'm positive this isn't the most effective way to just get the file path of an executable, and if anyone has another approach to this or has any idea as to why this is happening, it would be much appreciated.

Scornz
  • 380
  • 3
  • 14
  • Maybe someone has a more technically informative answer but my guess is when you include the debug lines, the process has a tiny bit more time to initialize to a ready state before accessing `MainModule`. Sounds odd but I’ve seen stranger things with `System.Diagnostics.Process`. For instance try placing `Thread.Sleep(1)` (or some different interval), instead of the debug lines, does it also work then? – blins Jun 23 '18 at 15:02
  • @blins I think you are right, it seems that it just needs a little bit more time to set it up. I added `Thread.Sleep(1)` and it worked as expected without the Debug statements, now I am just curious if there is a more "clean" way to get the same result. – Scornz Jun 23 '18 at 17:01
  • Try `process.WaitForInputIdle();`. See here: https://stackoverflow.com/questions/6390030/c-sharp-making-a-process-start-wait-until-the-process-has-start-up – blins Jun 23 '18 at 17:40

1 Answers1

0

The above example is actually a horrible way to approach this. Some processes won't kill, and the amount of time it takes to start a process varies drastically depending on what you are trying to start. I'd advise setting up a list of all installed programs, and sorting through that, which will be much more reliable.

Here is a link on how to approach that (Get installed applications in a system).

Scornz
  • 380
  • 3
  • 14