Firstly, you need to be a little more careful with your string literals, the code you posted won't compile because "\c" is not a valid string literal escape sequence. To fix:
string newPathComponent = @"C:\ccstg";
if (!path.Contains(newPathComponent))
{
if (!path.EndsWith(";"))
path = path + ';';
path = path + newPathComponent;
Environment.SetEnvironmentVariable("Path", path);
Now, this code works and sets the path for the duration of the process. If you want to set the path permanently, you need to use Environment.SetEnvironmentVariable Method (String, String, EnvironmentVariableTarget)
, for instance:
var target = EnvironmentVariableTarget.User; // Or EnvironmentVariableTarget.Machine
Environment.SetEnvironmentVariable("Path", path, target);
More here.
However, if you do that, you have to be careful to add your path component only to the path associated with that EnvironmentVariableTarget
. That's because the %PATH%
environment variable is actually combined from several sources. If you aren't careful, you may copy the combined path into just the EnvironmentVariableTarget.Machine
or EnvironmentVariableTarget.User
source -- which you do not want to do.
Thus:
static void AddToEnvironmentPath(string pathComponent, EnvironmentVariableTarget target)
{
string targetPath = System.Environment.GetEnvironmentVariable("Path", target) ?? string.Empty;
if (!string.IsNullOrEmpty(targetPath) && !targetPath.EndsWith(";"))
targetPath = targetPath + ';';
targetPath = targetPath + pathComponent;
Environment.SetEnvironmentVariable("Path", targetPath, target);
}
Finally, if you are running inside the Visual Studio Hosting Process for debugging, I have observed that if you use Environment.SetEnvironmentVariable("Path",path, EnvironmentVariableTarget.User)
, changes to the permanent environment will not be picked up until you exit and restart visual studio. Something weird to do with the visual studio hosting process, I reckon. To handle this odd scenario you might want to do both:
AddToEnvironmentPath(@"C:\ccstg", EnvironmentVariableTarget.User)
AddToEnvironmentPath(@"C:\ccstg", EnvironmentVariableTarget.Process)