-1

I have this code:

String path = Environment.ExpandEnvironmentVariables("%path%");  

And I have two unsolved problems:

  1. If I run the program in Visual Studio I get the path VS is running in.

    How can I change it?

If I type %path% in the standard windows cmd I get this: cmd.exe

In VS 2015 I get this output:

VS 2015

  1. If I run the program as normal, I get a string with all entries in the path variable.

How can I get only the first element of entries?

I already checked out this question

Community
  • 1
  • 1
tux007
  • 282
  • 1
  • 3
  • 17

1 Answers1

1
  1. Not sure what was the problem you're facing. The codes return the actual system environment variable value for me, even when it runs from VS 2015 (with or without debug).

  2. The environment variable entries is just semicolon separated string. So you should be able to do a simple String.Split() and take the first value returned : path.Split(';')[0]. The output in my system can be seen in the below screen capture.

enter image description here


UPDATE :

Regarding question no.1, turned out that OP wants to get the first entry of current machine's environment variable. For this purpose, we can use Environment.GetEnvironmentVariable() method instead, passing EnvironmentVariableTarget.Machine as the second parameter :

Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Machine).Split(';')[0]
har07
  • 88,338
  • 12
  • 84
  • 137
  • After looking at the uploaded picture, I think it is the first value of current machine's environment variable that you got. Try this way and let me know if it works correctly in your machine : `Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Machine).Split(';')[0]` – har07 Apr 02 '16 at 13:15