JasCav
JasCav

Reputation: 34632

Can't Access Windows Environment Variable with C#

I created an installer using WiX. One thing the installer does is sets an environment variable PLUGIN_DIRECTORY (it's at the system level).

Within some C# code that I have written, I need to access that variable so I can watch a certain directory. I do this via the following code:

FileSystemWatcher water = new FileSystemWatcher();
watcher.Path = Environment.GetEnvironmentVariable("PLUGIN_DIRECTORY") + "\\";

Unfortunately (and when I debug), all that watcher.Path is set to is "\".

Do I need to reboot after the install? I wouldn't see why as the variable is already set. Any other suggestions? I'm not getting any errors - it's just not watching the right path.

Thanks

Upvotes: 6

Views: 4591

Answers (4)

user374125
user374125

Reputation: 31

The system environment is inherited from parent, after update, other process can't recognized.

We could refresh process environment by load environment from "machine" and save to "process".

string SysEnvir = System.Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);

System.Environment.SetEnvironmentVariable("Path", SysEnvir, EnvironmentVariableTarget.Process);

Upvotes: 3

Jonas B
Jonas B

Reputation: 2391

I'm sorry if I'm terribly wrong I can't confirm this as I do not have a compiler installed. But you can try to use: watcher.Path = Environment.GetEnvironmentVariable("%PLUGIN_DIRECTORY%") + "\";

That is, %PLUGIN_DIRECTORY% instead of just PLUGIN_DIRECTORY.

Hope it was of any help

Upvotes: 0

Vivelin
Vivelin

Reputation: 787

Just to be sure, does PLUGIN_DIRECTORY have anything set after the installer has run?

Upvotes: 0

Motie Mediator
Motie Mediator

Reputation: 268

If you had visual studio open when you created the environment variable then I don't know if it will pick it up until you close and restart VS. When a process is started it inherits the environment variables from it's parent process. I'm not exactly sure how VS launches an executable after you build it but it probably is a sub process and as a result isn't picking up your new environment variable.

Upvotes: 13

Related Questions