Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3115
  • Last Modified:

setting environment variables in c#

I need to set an environment variable (give a new one) through c# coding in the installation process. the Environment class (system.environment) doesnt allow to do that, although environment variables can be read from it.
is there any way to do this. some other class which can do this or an work around ?

Sam
0
sampathbwelagedera
Asked:
sampathbwelagedera
  • 2
1 Solution
 
AlexFMCommented:
User environment variables are kept in the Registry key:
HKEY_CURRENT_USER\Environment

System environment variables are kept in the Registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

You need to set them using Registry functions.
0
 
Fahad MukhtarDistinguished EngineerCommented:
use the SetEnvironmentVariable api..

using System.Runtime.InteropServices;
.......

[DllImport("Kernel32.dll")]
static extern bool SetEnvironmentVariable(string name, string val);
.........
bool result = SetEnvironmentVariable("Var_Name", "Var_Value");
0
 
sampathbwelagederaAuthor Commented:
I Tryied Ales's method it works fine thanks for the tip.
 i'll try the method Desp had suggested as well.

/Sam
0
 
AlexFMCommented:
SetEnvironmentVariable works for the current process and for processes launched from it. It is not persistent. It depends on your purposes, which way to use.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now