// Copyright 2015, Igor Shaula // Licensed under the MIT License <LICENSE or // http://opensource.org/licenses/MIT>. This file // may not be copied, modified, or distributed // except according to those terms.
//! Crate for accessing MS Windows registry //! //!## Usage //! //!### Basic usage //! //!```toml,ignore //!# Cargo.toml //![dependencies] //!winreg = "0.10" //!``` //! //!```no_run //!extern crate winreg; //!use std::io; //!use std::path::Path; //!use winreg::enums::*; //!use winreg::RegKey; //! //!fn main() -> io::Result<()> { //! println!("Reading some system info..."); //! let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); //! let cur_ver = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion")?; //! let pf: String = cur_ver.get_value("ProgramFilesDir")?; //! let dp: String = cur_ver.get_value("DevicePath")?; //! println!("ProgramFiles = {}\nDevicePath = {}", pf, dp); //! let info = cur_ver.query_info()?; //! println!("info = {:?}", info); //! let mt = info.get_last_write_time_system(); //! println!( //! "last_write_time as winapi::um::minwinbase::SYSTEMTIME = {}-{:02}-{:02} {:02}:{:02}:{:02}", //! mt.wYear, mt.wMonth, mt.wDay, mt.wHour, mt.wMinute, mt.wSecond //! ); //! //! // enable `chrono` feature on `winreg` to make this work //! // println!( //! // "last_write_time as chrono::NaiveDateTime = {}", //! // info.get_last_write_time_chrono() //! // ); //! //! println!("And now lets write something..."); //! let hkcu = RegKey::predef(HKEY_CURRENT_USER); //! let path = Path::new("Software").join("WinregRsExample1"); //! let (key, disp) = hkcu.create_subkey(&path)?; //! //! match disp { //! REG_CREATED_NEW_KEY => println!("A new key has been created"), //! REG_OPENED_EXISTING_KEY => println!("An existing key has been opened"), //! } //! //! key.set_value("TestSZ", &"written by Rust")?; //! let sz_val: String = key.get_value("TestSZ")?; //! key.delete_value("TestSZ")?; //! println!("TestSZ = {}", sz_val); //! //! key.set_value("TestMultiSZ", &vec!["written", "by", "Rust"])?; //! let multi_sz_val: Vec<String> = key.get_value("TestMultiSZ")?; //! key.delete_value("TestMultiSZ")?; //! println!("TestMultiSZ = {:?}", multi_sz_val); //! //! key.set_value("TestDWORD", &1234567890u32)?; //! let dword_val: u32 = key.get_value("TestDWORD")?; //! println!("TestDWORD = {}", dword_val); //! //! key.set_value("TestQWORD", &1234567891011121314u64)?; //! let qword_val: u64 = key.get_value("TestQWORD")?; //! println!("TestQWORD = {}", qword_val); //! //! key.create_subkey("sub\\key")?; //! hkcu.delete_subkey_all(&path)?; //! //! println!("Trying to open nonexistent key..."); //! hkcu.open_subkey(&path).unwrap_or_else(|e| match e.kind() { //! io::ErrorKind::NotFound => panic!("Key doesn't exist"), //! io::ErrorKind::PermissionDenied => panic!("Access denied"), //! _ => panic!("{:?}", e), //! }); //! Ok(()) //!} //!``` //! //!### Iterators //! //!```no_run //!extern crate winreg; //!use std::io; //!use winreg::RegKey; //!use winreg::enums::*; //! //!fn main() -> io::Result<()> { //! println!("File extensions, registered in system:"); //! for i in RegKey::predef(HKEY_CLASSES_ROOT) //! .enum_keys().map(|x| x.unwrap()) //! .filter(|x| x.starts_with(".")) //! { //! println!("{}", i); //! } //! //! let system = RegKey::predef(HKEY_LOCAL_MACHINE) //! .open_subkey("HARDWARE\\DESCRIPTION\\System")?; //! for (name, value) in system.enum_values().map(|x| x.unwrap()) { //! println!("{} = {:?}", name, value); //! } //! //! Ok(()) //!} //!``` //! #[cfg(feature = "chrono")] externcrate chrono; #[cfg(feature = "serialization-serde")] externcrate serde; externcrate winapi; use enums::*; use std::default::Default; use std::ffi::OsStr; use std::fmt; use std::io; use std::mem::transmute; use std::os::windows::ffi::OsStrExt; use std::ptr; use std::slice; #[cfg(feature = "transactions")] use transaction::Transaction; use types::{FromRegValue, ToRegValue}; pubuse winapi::shared::minwindef::HKEY; use winapi::shared::minwindef::{BYTE, DWORD, FILETIME, LPBYTE}; use winapi::shared::winerror; use winapi::um::minwinbase::SYSTEMTIME; use winapi::um::timezoneapi::FileTimeToSystemTime; use winapi::um::winnt::{self, WCHAR}; use winapi::um::winreg as winapi_reg;
impl RegKeyMetadata { /// Returns `last_write_time` field as `winapi::um::minwinbase::SYSTEMTIME` pubfn get_last_write_time_system(&self) -> SYSTEMTIME { letmut st: SYSTEMTIME = unsafe { ::std::mem::zeroed() }; unsafe {
FileTimeToSystemTime(&self.last_write_time, &mut st);
}
st
}
/// Returns `last_write_time` field as `chrono::NaiveDateTime`. /// Part of `chrono` feature. #[cfg(feature = "chrono")] pubfn get_last_write_time_chrono(&self) -> chrono::NaiveDateTime { let st = self.get_last_write_time_system();
/// Load a registry hive from a file as an application hive. /// If `lock` is set to `true`, then the hive cannot be loaded again until /// it's unloaded (i.e. all keys from it go out of scope). /// /// # Examples /// /// ```no_run /// # use std::error::Error; /// # use winreg::RegKey; /// # use winreg::enums::*; /// # fn main() -> Result<(), Box<dyn Error>> { /// let handle = RegKey::load_app_key("C:\\myhive.dat", false)?; /// # Ok(()) /// # } /// ``` pubfn load_app_key<N: AsRef<OsStr>>(filename: N, lock: bool) -> io::Result<RegKey> { let options = if lock {
winapi_reg::REG_PROCESS_APPKEY
} else { 0
};
RegKey::load_app_key_with_flags(filename, enums::KEY_ALL_ACCESS, options)
}
/// Load a registry hive from a file as an application hive with desired /// permissions and options. If `options` is set to `REG_PROCESS_APPKEY`, /// then the hive cannot be loaded again until it's unloaded (i.e. all keys /// from it go out of scope). /// # Examples /// /// ```no_run /// # use std::error::Error; /// # use winreg::RegKey; /// # use winreg::enums::*; /// # fn main() -> Result<(), Box<dyn Error>> { /// let handle = RegKey::load_app_key_with_flags("C:\\myhive.dat", KEY_READ, 0)?; /// # Ok(()) /// # } /// ``` pubfn load_app_key_with_flags<N: AsRef<OsStr>>(
filename: N,
perms: winapi_reg::REGSAM,
options: DWORD,
) -> io::Result<RegKey> { let c_filename = to_utf16(filename); letmut new_hkey: HKEY = ptr::null_mut(); matchunsafe {
winapi_reg::RegLoadAppKeyW(c_filename.as_ptr(), &mut new_hkey, perms, options, 0) as DWORD
} { 0 => Ok(RegKey { hkey: new_hkey }),
err => werr!(err),
}
}
/// Return inner winapi HKEY of a key: /// /// # Examples /// /// ```no_run /// # use std::error::Error; /// # use winreg::RegKey; /// # use winreg::enums::*; /// # fn main() -> Result<(), Box<dyn Error>> { /// let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); /// let soft = hklm.open_subkey("SOFTWARE")?; /// let handle = soft.raw_handle(); /// # Ok(()) /// # } /// ``` pubconstfn raw_handle(&self) -> HKEY { self.hkey
}
/// Open subkey with `KEY_READ` permissions. /// Will open another handle to itself if `path` is an empty string. /// To open with different permissions use `open_subkey_with_flags`. /// You can also use `create_subkey` to open with `KEY_ALL_ACCESS` permissions. /// /// # Examples /// /// ```no_run /// # use std::error::Error; /// # use winreg::RegKey; /// # use winreg::enums::*; /// # fn main() -> Result<(), Box<dyn Error>> { /// let soft = RegKey::predef(HKEY_CURRENT_USER) /// .open_subkey("Software")?; /// # Ok(()) /// # } /// ``` pubfn open_subkey<P: AsRef<OsStr>>(&self, path: P) -> io::Result<RegKey> { self.open_subkey_with_flags(path, enums::KEY_READ)
}
/// Open subkey with desired permissions. /// Will open another handle to itself if `path` is an empty string. /// /// # Examples /// /// ```no_run /// # use std::error::Error; /// # use winreg::RegKey; /// # use winreg::enums::*; /// # fn main() -> Result<(), Box<dyn Error>> { /// let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); /// hklm.open_subkey_with_flags("SOFTWARE\\Microsoft", KEY_READ)?; /// # Ok(()) /// # } /// ``` pubfn open_subkey_with_flags<P: AsRef<OsStr>>(
&self,
path: P,
perms: winapi_reg::REGSAM,
) -> io::Result<RegKey> { let c_path = to_utf16(path); letmut new_hkey: HKEY = ptr::null_mut(); matchunsafe {
winapi_reg::RegOpenKeyExW(self.hkey, c_path.as_ptr(), 0, perms, &mut new_hkey) as DWORD
} { 0 => Ok(RegKey { hkey: new_hkey }),
err => werr!(err),
}
}
/// Create subkey (and all missing parent keys) /// and open it with `KEY_ALL_ACCESS` permissions. /// Will just open key if it already exists. /// If succeeds returns a tuple with the created subkey and its disposition, /// which can be `REG_CREATED_NEW_KEY` or `REG_OPENED_EXISTING_KEY`. /// Will open another handle to itself if `path` is an empty string. /// To create with different permissions use `create_subkey_with_flags`. /// /// # Examples /// /// ```no_run /// # use std::error::Error; /// # use winreg::RegKey; /// use winreg::enums::*; /// # fn main() -> Result<(), Box<dyn Error>> { /// let hkcu = RegKey::predef(HKEY_CURRENT_USER); /// let (settings, disp) = hkcu.create_subkey("Software\\MyProduct\\Settings")?; /// /// match disp { /// REG_CREATED_NEW_KEY => println!("A new key has been created"), /// REG_OPENED_EXISTING_KEY => println!("An existing key has been opened") /// } /// # Ok(()) /// # } /// ``` pubfn create_subkey<P: AsRef<OsStr>>(&self, path: P) -> io::Result<(RegKey, RegDisposition)> { self.create_subkey_with_flags(path, enums::KEY_ALL_ACCESS)
}
/// Recursively delete subkey with all its subkeys and values. /// If `path` is an empty string, the subkeys and values of this key are deleted. /// /// # Examples /// /// ```no_run /// # use std::error::Error; /// # use winreg::RegKey; /// # use winreg::enums::*; /// # fn main() -> Result<(), Box<dyn Error>> { /// RegKey::predef(HKEY_CURRENT_USER) /// .delete_subkey_all("Software\\MyProduct")?; /// # Ok(()) /// # } /// ``` pubfn delete_subkey_all<P: AsRef<OsStr>>(&self, path: P) -> io::Result<()> { let c_path; let path_ptr = if path.as_ref().is_empty() {
ptr::null()
} else {
c_path = to_utf16(path);
c_path.as_ptr()
}; matchunsafe {
winapi_reg::RegDeleteTreeW( self.hkey,
path_ptr, //If this parameter is NULL, the subkeys and values of this key are deleted.
) as DWORD
} { 0 => Ok(()),
err => werr!(err),
}
}
/// Get a value from registry and seamlessly convert it to the specified rust type /// with `FromRegValue` implemented (currently `String`, `u32` and `u64`). /// Will get the `Default` value if `name` is an empty string. /// /// # Examples /// /// ```no_run /// # use std::error::Error; /// # use winreg::RegKey; /// # use winreg::enums::*; /// # fn main() -> Result<(), Box<dyn Error>> { /// let hkcu = RegKey::predef(HKEY_CURRENT_USER); /// let settings = hkcu.open_subkey("Software\\MyProduct\\Settings")?; /// let server: String = settings.get_value("server")?; /// let port: u32 = settings.get_value("port")?; /// # Ok(()) /// # } /// ``` pubfn get_value<T: FromRegValue, N: AsRef<OsStr>>(&self, name: N) -> io::Result<T> { matchself.get_raw_value(name) {
Ok(ref val) => FromRegValue::from_reg_value(val),
Err(err) => Err(err),
}
}
/// Get raw bytes from registry value. /// Will get the `Default` value if `name` is an empty string. /// /// # Examples /// /// ```no_run /// # use std::error::Error; /// # use winreg::RegKey; /// # use winreg::enums::*; /// # fn main() -> Result<(), Box<dyn Error>> { /// let hkcu = RegKey::predef(HKEY_CURRENT_USER); /// let settings = hkcu.open_subkey("Software\\MyProduct\\Settings")?; /// let data = settings.get_raw_value("data")?; /// println!("Bytes: {:?}", data.bytes); /// # Ok(()) /// # } /// ``` pubfn get_raw_value<N: AsRef<OsStr>>(&self, name: N) -> io::Result<RegValue> { let c_name = to_utf16(name); letmut buf_len: DWORD = 2048; letmut buf_type: DWORD = 0; letmut buf: Vec<u8> = Vec::with_capacity(buf_len as usize); loop { matchunsafe {
winapi_reg::RegQueryValueExW( self.hkey,
c_name.as_ptr() as *const u16,
ptr::null_mut(),
&mut buf_type,
buf.as_mut_ptr() as LPBYTE,
&mut buf_len,
) as DWORD
} { 0 => { unsafe {
buf.set_len(buf_len as usize);
} // minimal check before transmute to RegType if buf_type > winnt::REG_QWORD { return werr!(winerror::ERROR_BAD_FILE_TYPE);
} let t: RegType = unsafe { transmute(buf_type as u8) }; return Ok(RegValue {
bytes: buf,
vtype: t,
});
}
winerror::ERROR_MORE_DATA => {
buf.reserve(buf_len as usize);
}
err => return werr!(err),
}
}
}
/// Seamlessly convert a value from a rust type and write it to the registry value /// with `ToRegValue` trait implemented (currently `String`, `&str`, `u32` and `u64`). /// Will set the `Default` value if `name` is an empty string. /// /// # Examples /// /// ```no_run /// # use std::error::Error; /// # use winreg::RegKey; /// # use winreg::enums::*; /// # fn main() -> Result<(), Box<dyn Error>> { /// let hkcu = RegKey::predef(HKEY_CURRENT_USER); /// let (settings, disp) = hkcu.create_subkey("Software\\MyProduct\\Settings")?; /// settings.set_value("server", &"www.example.com")?; /// settings.set_value("port", &8080u32)?; /// # Ok(()) /// # } /// ``` pubfn set_value<T: ToRegValue, N: AsRef<OsStr>>(&self, name: N, value: &T) -> io::Result<()> { self.set_raw_value(name, &value.to_reg_value())
}
/// Write raw bytes from `RegValue` struct to a registry value. /// Will set the `Default` value if `name` is an empty string. /// /// # Examples /// /// ```no_run /// # use std::error::Error; /// use winreg::{RegKey, RegValue}; /// use winreg::enums::*; /// # fn main() -> Result<(), Box<dyn Error>> { /// let hkcu = RegKey::predef(HKEY_CURRENT_USER); /// let settings = hkcu.open_subkey("Software\\MyProduct\\Settings")?; /// let bytes: Vec<u8> = vec![1, 2, 3, 5, 8, 13, 21, 34, 55, 89]; /// let data = RegValue{ vtype: REG_BINARY, bytes: bytes}; /// settings.set_raw_value("data", &data)?; /// println!("Bytes: {:?}", data.bytes); /// # Ok(()) /// # } /// ``` pubfn set_raw_value<N: AsRef<OsStr>>(&self, name: N, value: &RegValue) -> io::Result<()> { let c_name = to_utf16(name); let t = value.vtype.clone() as DWORD; matchunsafe {
winapi_reg::RegSetValueExW( self.hkey,
c_name.as_ptr(), 0,
t,
value.bytes.as_ptr() as *const BYTE,
value.bytes.len() as u32,
) as DWORD
} { 0 => Ok(()),
err => werr!(err),
}
}
/// Delete specified value from registry. /// Will delete the `Default` value if `name` is an empty string. /// /// # Examples /// /// ```no_run /// # use std::error::Error; /// # use winreg::RegKey; /// # use winreg::enums::*; /// # fn main() -> Result<(), Box<dyn Error>> { /// let hkcu = RegKey::predef(HKEY_CURRENT_USER); /// let settings = hkcu.open_subkey("Software\\MyProduct\\Settings")?; /// settings.delete_value("data")?; /// # Ok(()) /// # } /// ``` pubfn delete_value<N: AsRef<OsStr>>(&self, name: N) -> io::Result<()> { let c_name = to_utf16(name); matchunsafe { winapi_reg::RegDeleteValueW(self.hkey, c_name.as_ptr()) as DWORD } { 0 => Ok(()),
err => werr!(err),
}
}
¤ Diese beiden folgenden Angebotsgruppen bietet das Unternehmen0.72Angebot
(Wie Sie bei der Firma Beratungs- und Dienstleistungen beauftragen können 2026-06-19)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.