2 // RegistryKey.cs: a single node in the Windows registry
5 // Miguel de Icaza (miguel@ximian.com)
6 // Erik LeBel (eriklebel@yahoo.ca)
7 // Gert Driesen (drieseng@users.sourceforge.net)
10 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Collections;
37 using System.Diagnostics;
38 using System.Runtime.InteropServices;
39 using System.Security;
41 using System.Security.AccessControl;
42 using System.Security.Permissions;
43 using Microsoft.Win32.SafeHandles;
45 namespace Microsoft.Win32
48 /// Wrapper class for Windows Registry Entry.
51 public sealed class RegistryKey : MarshalByRefObject, IDisposable
54 // This represents the backend data, used when creating the
59 SafeRegistryHandle safe_handle;
62 object hive; // the RegistryHive if the key represents a base key
63 readonly string qname; // the fully qualified registry key name
64 readonly bool isRemoteRoot; // is an instance of a remote root key?
65 readonly bool isWritable; // is the key openen in writable mode
67 static readonly IRegistryApi RegistryApi;
71 if (Path.DirectorySeparatorChar == '\\')
72 RegistryApi = new Win32RegistryApi ();
74 RegistryApi = new UnixRegistryApi ();
78 /// Construct an instance of a root registry key entry.
80 internal RegistryKey (RegistryHive hiveId) : this (hiveId,
81 new IntPtr ((int) hiveId), false)
86 /// Construct an instance of a root registry key entry.
88 internal RegistryKey (RegistryHive hiveId, IntPtr keyHandle, bool remoteRoot)
92 qname = GetHiveName (hiveId);
93 isRemoteRoot = remoteRoot;
94 isWritable = true; // always consider root writable
98 /// Construct an instance of a registry key entry.
100 internal RegistryKey (object data, string keyName, bool writable)
104 isWritable = writable;
110 /// Dispose of registry key object. Close the
111 /// key if it's still open.
114 public void Dispose ()
116 void IDisposable.Dispose ()
119 GC.SuppressFinalize (this);
125 /// Final cleanup of registry key object. Close the
126 /// key if it's still open.
135 /// Get the fully qualified registry key name.
138 get { return qname; }
143 /// Flush the current registry state to disk.
147 RegistryApi.Flush (this);
152 /// Close the current registry key and flushes the state of the registry
159 // a handle to a remote hive must be closed, while one to a local
160 // hive should not be closed
161 if (!isRemoteRoot && IsRoot)
164 RegistryApi.Close (this);
167 if (safe_handle != null) {
168 safe_handle.Close ();
176 /// get the number of sub-keys for this key
178 public int SubKeyCount {
180 AssertKeyStillValid ();
182 return RegistryApi.SubKeyCount (this);
188 /// get the number of values for this key
190 public int ValueCount {
192 AssertKeyStillValid ();
194 return RegistryApi.ValueCount (this);
200 [MonoTODO ("Not implemented in Unix")]
201 public SafeRegistryHandle Handle {
203 AssertKeyStillValid ();
205 if (safe_handle == null) {
206 IntPtr h = RegistryApi.GetHandle (this);
207 safe_handle = new SafeRegistryHandle (h, true);
215 [MonoLimitation ("View is ignored in Mono.")]
216 public RegistryView View {
218 return RegistryView.Default;
225 /// Set a registry value.
227 public void SetValue (string name, object value)
229 AssertKeyStillValid ();
232 throw new ArgumentNullException ("value");
235 AssertKeyNameLength (name);
238 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
240 RegistryApi.SetValue (this, name, value);
244 public void SetValue (string name, object value, RegistryValueKind valueKind)
246 AssertKeyStillValid ();
249 throw new ArgumentNullException ("value");
252 AssertKeyNameLength (name);
255 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
257 RegistryApi.SetValue (this, name, value, valueKind);
261 /// Open the sub key specified, for read access.
263 public RegistryKey OpenSubKey (string name)
265 return OpenSubKey (name, false);
270 /// Open the sub key specified.
272 public RegistryKey OpenSubKey (string name, bool writable)
274 AssertKeyStillValid ();
277 throw new ArgumentNullException ("name");
279 AssertKeyNameLength (name);
281 return RegistryApi.OpenSubKey (this, name, writable);
286 /// Get a registry value.
288 public object GetValue (string name)
290 return GetValue (name, null);
295 /// Get a registry value.
297 public object GetValue (string name, object defaultValue)
299 AssertKeyStillValid ();
301 return RegistryApi.GetValue (this, name, defaultValue,
302 RegistryValueOptions.None);
306 public object GetValue (string name, object defaultValue, RegistryValueOptions options)
308 AssertKeyStillValid ();
310 return RegistryApi.GetValue (this, name, defaultValue, options);
314 public RegistryValueKind GetValueKind (string name)
316 return RegistryApi.GetValueKind (this, name);
320 /// Create a sub key.
322 public RegistryKey CreateSubKey (string subkey)
324 AssertKeyStillValid ();
325 AssertKeyNameNotNull (subkey);
326 AssertKeyNameLength (subkey);
329 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
330 return RegistryApi.CreateSubKey (this, subkey);
334 [MonoLimitation ("permissionCheck is ignored in Mono")]
335 public RegistryKey CreateSubKey (string subkey, RegistryKeyPermissionCheck permissionCheck)
337 return CreateSubKey (subkey);
341 [MonoLimitation ("permissionCheck and registrySecurity are ignored in Mono")]
342 public RegistryKey CreateSubKey (string subkey, RegistryKeyPermissionCheck permissionCheck, RegistrySecurity registrySecurity)
344 return CreateSubKey (subkey);
349 [MonoLimitation ("permissionCheck is ignored in Mono")]
350 public RegistryKey CreateSubKey (string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions options)
352 AssertKeyStillValid ();
353 AssertKeyNameNotNull (subkey);
354 AssertKeyNameLength (subkey);
357 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
359 return RegistryApi.CreateSubKey (this, subkey, options);
363 [MonoLimitation ("permissionCheck and registrySecurity are ignored in Mono")]
364 public RegistryKey CreateSubKey (string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions options,
365 RegistrySecurity registrySecurity)
367 return CreateSubKey (subkey, permissionCheck, options);
373 /// Delete the specified subkey.
375 public void DeleteSubKey(string subkey)
377 DeleteSubKey (subkey, true);
382 /// Delete the specified subkey.
384 public void DeleteSubKey(string subkey, bool throwOnMissingSubKey)
386 AssertKeyStillValid ();
387 AssertKeyNameNotNull (subkey);
388 AssertKeyNameLength (subkey);
391 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
393 RegistryKey child = OpenSubKey (subkey);
396 if (throwOnMissingSubKey)
397 throw new ArgumentException ("Cannot delete a subkey tree"
398 + " because the subkey does not exist.");
402 if (child.SubKeyCount > 0){
403 throw new InvalidOperationException ("Registry key has subkeys"
404 + " and recursive removes are not supported by this method.");
409 RegistryApi.DeleteKey (this, subkey, throwOnMissingSubKey);
414 /// Delete a sub tree (node, and values alike).
416 public void DeleteSubKeyTree(string subkey)
418 DeleteSubKeyTree (subkey, true);
424 void DeleteSubKeyTree (string subkey, bool throwOnMissingSubKey)
426 // Note: this is done by deleting sub-nodes recursively.
427 // The preformance is not very good. There may be a
428 // better way to implement this.
430 AssertKeyStillValid ();
431 AssertKeyNameNotNull (subkey);
432 AssertKeyNameLength (subkey);
434 RegistryKey child = OpenSubKey (subkey, true);
436 if (!throwOnMissingSubKey)
439 throw new ArgumentException ("Cannot delete a subkey tree"
440 + " because the subkey does not exist.");
443 child.DeleteChildKeysAndValues ();
445 DeleteSubKey (subkey, false);
450 /// Delete a value from the registry.
452 public void DeleteValue(string name)
454 DeleteValue (name, true);
459 /// Delete a value from the registry.
461 public void DeleteValue(string name, bool throwOnMissingValue)
463 AssertKeyStillValid ();
466 throw new ArgumentNullException ("name");
469 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
471 RegistryApi.DeleteValue (this, name, throwOnMissingValue);
474 public RegistrySecurity GetAccessControl ()
476 throw new NotImplementedException ();
479 public RegistrySecurity GetAccessControl (AccessControlSections includeSections)
481 throw new NotImplementedException ();
486 /// Get the names of the sub keys.
488 public string[] GetSubKeyNames()
490 AssertKeyStillValid ();
492 return RegistryApi.GetSubKeyNames (this);
497 /// Get the names of values contained in this key.
499 public string[] GetValueNames()
501 AssertKeyStillValid ();
502 return RegistryApi.GetValueNames (this);
507 [SecurityPermission (SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
508 [MonoTODO ("Not implemented on unix")]
509 public static RegistryKey FromHandle (SafeRegistryHandle handle)
512 throw new ArgumentNullException ("handle");
514 return RegistryApi.FromHandle (handle);
518 [SecurityPermission (SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
519 [MonoTODO ("Not implemented on unix")]
520 public static RegistryKey FromHandle (SafeRegistryHandle handle, RegistryKey view)
522 return FromHandle (handle);
527 [MonoTODO ("Not implemented on unix")]
528 public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey,string machineName)
530 if (machineName == null)
531 throw new ArgumentNullException ("machineName");
532 return RegistryApi.OpenRemoteBaseKey (hKey, machineName);
537 [MonoTODO ("Not implemented on unix")]
538 public static RegistryKey OpenRemoteBaseKey (RegistryHive hKey, string machineName, RegistryView view)
540 if (machineName == null)
541 throw new ArgumentNullException ("machineName");
542 return RegistryApi.OpenRemoteBaseKey (hKey, machineName);
546 [MonoLimitation ("View is ignored in Mono")]
547 public static RegistryKey OpenBaseKey (RegistryHive hKey, RegistryView view)
550 case RegistryHive.ClassesRoot:
551 return Registry.ClassesRoot;
552 case RegistryHive.CurrentConfig:
553 return Registry.CurrentConfig;
554 case RegistryHive.CurrentUser:
555 return Registry.CurrentUser;
556 case RegistryHive.DynData:
557 return Registry.DynData;
558 case RegistryHive.LocalMachine:
559 return Registry.LocalMachine;
560 case RegistryHive.PerformanceData:
561 return Registry.PerformanceData;
562 case RegistryHive.Users:
563 return Registry.Users;
566 throw new ArgumentException ("hKey");
571 [MonoLimitation ("permissionCheck is ignored in Mono")]
572 public RegistryKey OpenSubKey (string name, RegistryKeyPermissionCheck permissionCheck)
574 return OpenSubKey (name);
578 [MonoLimitation ("permissionCheck and rights are ignored in Mono")]
579 public RegistryKey OpenSubKey (string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights)
581 return OpenSubKey (name);
584 public void SetAccessControl (RegistrySecurity registrySecurity)
586 throw new NotImplementedException ();
591 /// Build a string representation of the registry key.
592 /// Conatins the fully qualified key name, and the Hex
593 /// representation of the registry key handle.
595 public override string ToString()
597 AssertKeyStillValid ();
599 return RegistryApi.ToString (this);
602 #endregion // PublicAPI
604 internal bool IsRoot {
605 get { return hive != null; }
608 private bool IsWritable {
609 get { return isWritable; }
612 internal RegistryHive Hive {
615 throw new NotSupportedException ();
616 return (RegistryHive) hive;
620 // returns the key handle for the win32 implementation and the
621 // KeyHandler for the unix implementation
622 internal object InternalHandle {
623 get { return handle; }
627 /// validate that the registry key handle is still usable.
629 private void AssertKeyStillValid ()
632 throw new ObjectDisposedException ("Microsoft.Win32.RegistryKey");
637 /// validate that the registry key handle is still usable, and
638 /// that the 'subKeyName' is not null.
640 private void AssertKeyNameNotNull (string subKeyName)
642 if (subKeyName == null)
643 throw new ArgumentNullException ("name");
646 private void AssertKeyNameLength (string name)
648 if (name.Length > 255)
649 throw new ArgumentException ("Name of registry key cannot be greater than 255 characters");
653 /// Utility method to delelte a key's sub keys and values.
654 /// This method removes a level of indirection when deleting
657 private void DeleteChildKeysAndValues ()
662 string[] subKeys = GetSubKeyNames ();
663 foreach (string subKey in subKeys)
665 RegistryKey sub = OpenSubKey (subKey, true);
666 sub.DeleteChildKeysAndValues ();
668 DeleteSubKey (subKey, false);
671 string[] values = GetValueNames ();
672 foreach (string value in values) {
673 DeleteValue (value, false);
678 /// decode a byte array as a string, and strip trailing nulls
680 static internal string DecodeString (byte[] data)
682 string stringRep = Encoding.Unicode.GetString (data);
683 int idx = stringRep.IndexOf ('\0');
685 stringRep = stringRep.TrimEnd ('\0');
689 static internal IOException CreateMarkedForDeletionException ()
691 throw new IOException ("Illegal operation attempted on a"
692 + " registry key that has been marked for deletion.");
695 static string GetHiveName (RegistryHive hive)
698 case RegistryHive.ClassesRoot:
699 return "HKEY_CLASSES_ROOT";
700 case RegistryHive.CurrentConfig:
701 return "HKEY_CURRENT_CONFIG";
702 case RegistryHive.CurrentUser:
703 return "HKEY_CURRENT_USER";
704 case RegistryHive.DynData:
705 return "HKEY_DYN_DATA";
706 case RegistryHive.LocalMachine:
707 return "HKEY_LOCAL_MACHINE";
708 case RegistryHive.PerformanceData:
709 return "HKEY_PERFORMANCE_DATA";
710 case RegistryHive.Users:
714 throw new NotImplementedException (string.Format (
715 "Registry hive '{0}' is not implemented.", hive.ToString ()));