Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't Access Windows Environment Variable with C#

Tags:

c#

windows

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

like image 364
JasCav Avatar asked Sep 17 '09 18:09

JasCav


People also ask

How do I pass an environment variable from the command line?

To set (or change) a environment variable, use command " set varname=value ". There shall be no spaces before and after the '=' sign. To unset an environment variable, use " set varname= ", i.e., set it to an empty string.

How do I fix Windows environment variables?

Go to "My Computer" properties -> "Advanced system settings" -> click on "Advanced" tab -> click on "Environment Variables" button -> Edit "PATH" variable and paste everything copied in the third step in -> Variable value: box. Click OK in all the opened windows.

How do I view a variable in CMD?

Select Start > All Programs > Accessories > Command Prompt. In the command window that opens, enter set. A list of all the environment variables that are set is displayed in the command window.

How do I access system environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables.


2 Answers

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.

like image 132
Motie Mediator Avatar answered Nov 14 '22 21:11

Motie Mediator


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);
like image 29
user374125 Avatar answered Nov 14 '22 22:11

user374125