Home > Net >  Can GetEnvironmentVariable("PATH") really return null?
Can GetEnvironmentVariable("PATH") really return null?

Time:10-15

This question may be a little less about C# and more about operating systems, please tell me if I should use other tags.

I need to find out if a user has Python installed, I thought checking for python.exe inside directories with "Python" in PATH was good enough, so I did:

string[] path = Environment.GetEnvironmentVariable("PATH").Split(';');
foreach (string directory in path)
{
    if (directory.Contains("Python")
    {
        ...
    }
}

Thing is, GetEnvironmentVariable can return null and the responsible thing to do would be to make sure is not null before doing Split() and then putting it's value in string[] path.

But, really... is there any real scenario in which GetEnvironmentVariable("PATH") would return null?

CodePudding user response:

I don't think I've even seen it in practice. I'm thinking it could only happen because of bugs or malicious behavior.

  • Programs can change the environment of children by passing a parameter to CreateProcess and I suppose a bug or configuration issue could cause it to not set %path%. It is rare for programs to do this in the first place so it is an unlikely scenario.

  • Build systems might erase everything to ensure reproducible builds but it would only stay in this state for a short while during startup and never propagate this environment to children.

  • Someone playing around in cmd.exe and doing set "path=" or running a buggy batch file. I find this to be the most likely scenario.

However unlikely, it would be a bit embarrassing for your app to crash with an exception because of this when you should be able to prevent it with an extra line or two of code...

  • Related