1

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.
  • 2
    https://stackoverflow.com/questions/37906715/reading-the-environment-variables-of-another-process - Raymond Chen says it's can't be done reliably and https://stackoverflow.com/questions/38660262/how-to-get-other-processs-environment-variable-using-c-sharp links to a blog with a hack that scrapes the other process's memory to get the variables, which may work for you or may not. Given what Raymond knows about Windows I'd not get my hopes up much – Caius Jard Jul 09 '20 at 08:38
  • 2
    What error do you get with the posted code? Have you looked at the answers to [this question](https://stackoverflow.com/questions/38660262/how-to-get-other-processs-environment-variable-using-c-sharp) and [this question](https://stackoverflow.com/questions/5470698/read-environment-variables-from-a-process-in-c-sharp)? – Rufus L Jul 09 '20 at 08:43
  • I edited my post with the error message. –  Jul 09 '20 at 12:03
  • Does this answer your question? [How to get other process's environment variable using c#](https://stackoverflow.com/questions/38660262/how-to-get-other-processs-environment-variable-using-c-sharp) – phuclv Dec 11 '22 at 09:36
  • The error was clear: *`System.InvalidOperationException`: Process was not started by this object, so requested information cannot be determined*. Obviously you have to **run a process elevated in order to read other processes' data**. How on earth can a normal process read sensitive data in other processes? – phuclv Dec 11 '22 at 09:37

1 Answers1

0

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