14

I am trying to set path environment variable for MySql.

I don't get an error, but my code doesn't work.

Code:

First:

string pathvar = @";C:\Program Files\MySQL\MySQL Server 5.1\bin\\";
System.Environment.SetEnvironmentVariable("PATH", pathvar);

Second:

string pathvar = System.Environment.GetEnvironmentVariable("PATH");
System.Environment.SetEnvironmentVariable("PATH", pathvar + @";C:\Program Files\MySQL\MySQL Server 5.1\bin\\");

Thank you for your help...

Govinda Rajbhar
  • 2,926
  • 6
  • 37
  • 62
user3313131
  • 583
  • 2
  • 7
  • 9
  • 2
    Tru to change `@";C:\Program Files\MySQL\MySQL Server 5.1\bin\\"` to `@";C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\"` – Rodion Feb 28 '14 at 11:20
  • 3
    while using @ no need to set "\" as "\\" , @ before string will result no char, on string that follows, to act as a special char. – knightsb Feb 28 '14 at 11:24

2 Answers2

22

You are associating the environment variable with your program, but instead you want to associate it with your local machine in order to make it available to every program. Look at the overload that takes an EnvironmentVariableTarget.

var name = "PATH";
var scope = EnvironmentVariableTarget.Machine; // or User
var oldValue = Environment.GetEnvironmentVariable(name, scope);
var newValue  = oldValue + @";C:\Program Files\MySQL\MySQL Server 5.1\bin\\";
Environment.SetEnvironmentVariable(name, newValue, scope);
Steven Liekens
  • 13,266
  • 8
  • 59
  • 85
  • Indeed. EnvironmentVariableTarget.Machine; is probably what the he needs. – KoalaBear Feb 28 '14 at 11:35
  • 1
    You're right. I thought that %PATH% is defined per-user, but apparently it's not. – Steven Liekens Feb 28 '14 at 11:37
  • @StevenLiekens `PATH` is defined *both* per-user *and* per-machine. The effective `PATH` is the concatenation of both. Which to modify depends on the specific case. – Franklin Yu Oct 30 '18 at 15:47
  • 1
    Copy-pasting this code may result in a **BUG**: GetEnvironmentVariable returns the concatenated path of user and machine, if you do not specify a target. This code would get the total, concatinated path, add something to it, and write it to the machine target. This would duplicate the user path onto the machine path! – Whosdatdev Feb 20 '20 at 00:27
  • 2
    Good eye @Whosdatdev, fixed! – Steven Liekens Feb 20 '20 at 12:05
2

Calling SetEnvironmentVariable has no effect on the system environment variables. Check this answer here:

https://stackoverflow.com/a/19705691/1057667

Community
  • 1
  • 1
Sunny Sharma
  • 4,688
  • 5
  • 35
  • 73