Search code examples
c#processenvironment-variablesazure-service-fabricprocessstartinfo

Get environment variables of a different process


I'm working with Service Fabric and I would like to create an observer of environment variables of selected processes.

I thought about this method:

var processes = Process.GetProcessesByName(processName);
foreach (var process in processes){
    var environmentVariables = process.StartInfo.EnvironmentVariables;
    foreach (DictionaryEntry envVar in environmentVariables){
        // envVar.Key, enVar.Value ...
    }
}

But I can't use StartInfo because processes are not launched here. Is there any other way to retrieve environement variables (key/value) of processes (retrieved by GetProcessByName/ID) ?

Error:

System.InvalidOperationException: Process was not started by this object, so requested information cannot be determined.

Solution

  • Within links posted I found Oleksiy Gapotchenko's blog. He developed a ready-to-use nuget package.

    Reads environment variables of a process. The functionality is achieved by reading the process environment block (PEB) at the operating system level.

    blog.gapotchenko/reading-environment-variables

    github/Gapotchenko.FX.Diagnostics.Process

    nuget/packages/Gapotchenko.FX.Diagnostics.Process