Reputation: 304
I am building a command-line application and I am using rust...
I know how to set system environment variables using a batch script, but I want to implement everything in rust, so is there a way to set environment variables for Windows using rust.
I tried set_var(KEY)
but it only works for the currently running process...
Upvotes: 3
Views: 3731
Reputation: 7575
To whom it may concern: Setting a system-wide environment variable is quite similar...
use winreg::{RegKey, HKEY_LOCAL_MACHINE};
fn main() {
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let env_key = hklm.create_subkey("System\\CurrentControlSet\\Control\\Session Manager\\Environment").unwrap();
env_key.set_value("MY_VAR", "my_value").unwrap();
}
Always remember: Modifying the registry requires administrative privileges.
Upvotes: 0
Reputation: 2917
You'll need to use the registry to do this, so a necessary disclaimer: using the registry incorrectly can mess up your system.
On Windows, user environment variables are stored in HKEY_CURRENT_USER\Environment\
. The Rust library winreg makes this pretty straightforward:
use winreg::{enums::*, RegKey};
fn main() {
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let (env, _) = hkcu.create_subkey("Environment").unwrap(); // create_subkey opens with write permissions
env.set_value("TestVar", &"TestValue").unwrap();
}
Upvotes: 4