How to get other process's environment variable using c# [duplicate]

喜欢而已 提交于 2021-02-10 07:25:33

问题


I have an elevated process and I'm trying to extract an environment variable from another process using C#. I know that the variable exists by using Process Explorer.

I can get the process environment variables like the following:

Process process = Process.GetProcessesByName("someprocess").First();
string value = process.StartInfo.EnvironmentVariables["var_name"];

But StartInfo only returns a subset of the process env variables, passed to process.Start().

How can I get environment variables that have bee set during process run time?


回答1:


It is not well documented, but ProcessStartInfo.EnvironmentVariables does not return the environment of a specific process.

If you look at the reference source, you will see that under the hood the GetEnvironmentStrings function is called. This function returns "a pointer to a block of memory that contains the environment variables of the calling process (both the system and the user environment variables)".

Accessing the environment block of another process is a bit more tricky. Oleksiy Gapotchenko has written an excellent blog post and also provides a sample solution.




回答2:


From what I can find it looks like that's simply not an action supported out-of-the-box.

The closest thing is Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process);

Unfortunately that seems to be "locked" to the current process. If there were just a way to set what process to target you'd be golden.

Fortunately, Microsoft provides a "reference source" you can use to see what the underlying code in .NET is (in this case http://referencesource.microsoft.com/#mscorlib/system/environment.cs,20e3d8aa4eb8f4b1). If the function supports doing what you want you could make your own wrapper for it.

If you trace that down you find a Win32 call in an unsafe context is ultimately responsible: http://referencesource.microsoft.com/mscorlib/R/c48702b7df790f4c.html

It looks like even that call is locked to the current process, so you'll need to write your own code for it. Here's an example in C (or C++, can't tell lol): http://www.codeproject.com/Articles/25647/Read-Environment-Strings-of-Remote-Process

You can translate the gist of that into unsafe C# and do the same thing using DllImports, etc. as necessary.. Sorry the answer isn't that easy, but it sounds like a fun project to me!

Edit: Oh I love how the linked possible duplicate did the same research that I did, found the same things, heh.. Just know that I didn't just copy-paste, did the research myself..



来源:https://stackoverflow.com/questions/38660262/how-to-get-other-processs-environment-variable-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!