This blog has moved to Medium

Subscribe via email

Reading enviornment variables from external processes in C#

I was trying to discern which of 3 java processes is our Tomcat process, to kill rouge Tomcats in our unit tests. We have code that uses Process.GetProcessesByName(), and checks the returned StartInfo.

Apparently, Process.GetProcess() returns empty StartInfo.

Digging around, I failed to find a ready-out-of-the-box way to do this. This StackOverflow article pointed me in the right direction of this CodeProject page.

My final result includes:

  1. A small utility that reads either all enviornment variables from some process, or a specific one.
  2. A small C# wrapper

Here is the usage:

private static string GetJavaWorkingDir(int pid)
  string processEnvReader = @"Scripts\ReadProcessEnv\bin\ReadProcessEnv.exe";
  ProcessEnvReader reader = new ProcessEnvReader(processEnvReader);
  return reader.Read(pid, "catalina_base");