Last active
August 29, 2015 14:08
-
-
Save sirtony/bda1b47ccc62484f7e78 to your computer and use it in GitHub Desktop.
A simple class to modify environment variables (Windows-only).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module envy; | |
version( Windows ): | |
private { | |
import std.windows.registry; | |
} | |
private enum ENV_KEY = "Environment"; | |
public enum EnvironmentScope | |
{ | |
System, | |
User, | |
} | |
public final class EnvironmentVariable | |
{ | |
private Key _root; | |
private string _name; | |
private string _value; | |
public string name() @property | |
{ | |
return this._name; | |
} | |
public string value() @property | |
{ | |
return this._value; | |
} | |
public void value( string str ) @property | |
{ | |
this._value = str; | |
} | |
public this( string name, EnvironmentScope scope_ = EnvironmentScope.User ) | |
{ | |
this._name = name; | |
string[] path = [ ]; | |
final switch( scope_ ) | |
{ | |
case EnvironmentScope.System: | |
this._root = Registry.localMachine(); | |
path = [ "SYSTEM", "CurrentControlSet", "Control", "Session Manager" ]; | |
break; | |
case EnvironmentScope.User: | |
this._root = Registry.currentUser(); | |
break; | |
} | |
path ~= ENV_KEY; | |
foreach( n; path ) | |
this._root = this._root.getKey( n ); | |
this.value = this._root.getValue( name ).value_EXPAND_SZ; | |
} | |
public EnvironmentVariable opAssign( string str ) | |
{ | |
this.value = str; | |
return this; | |
} | |
public EnvironmentVariable opOpAssign( string op )( string str ) if( op == "~=" ) | |
{ | |
this.value ~= str; | |
return this; | |
} | |
public void remove() | |
{ | |
this._root.deleteValue( this.name ); | |
this._root.flush(); | |
} | |
public void update() | |
{ | |
this._root.setValue( this.name, this.value ); | |
this._root.flush(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.stdio : writeln; | |
import std.path : pathSeparator; | |
import std.array : split; | |
import envy; | |
//Prints the PATH environment variable for the current user. | |
void main() | |
{ | |
auto path = new EnvironmentVariable( "PATH" ); | |
path.value.split( pathSeparator ).writeln(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment