Merge pull request #225 from mistoll/master
[mono.git] / mcs / class / corlib / Microsoft.Win32 / RegistryKey.cs
1 //
2 // RegistryKey.cs: a single node in the Windows registry
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Erik LeBel (eriklebel@yahoo.ca)
7 //   Gert Driesen (drieseng@users.sourceforge.net)
8 //
9 //
10 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
11 //
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:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
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.
30 //
31
32 #if !NET_2_1
33
34 using System;
35 using System.IO;
36 using System.Collections;
37 using System.Diagnostics;
38 using System.Runtime.InteropServices;
39 using System.Security;
40 using System.Text;
41 using System.Security.AccessControl;
42 using System.Security.Permissions;
43 using Microsoft.Win32.SafeHandles;
44
45 namespace Microsoft.Win32
46 {
47         /// <summary>
48         ///     Wrapper class for Windows Registry Entry.
49         /// </summary>
50         [ComVisible (true)]
51         public sealed class RegistryKey : MarshalByRefObject, IDisposable 
52         {
53                 //
54                 // This represents the backend data, used when creating the
55                 // RegistryKey object
56                 //
57                 object handle;
58 #if NET_4_0
59                 SafeRegistryHandle safe_handle;
60 #endif
61
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
66
67                 static readonly IRegistryApi RegistryApi;
68
69                 static RegistryKey ()
70                 {
71                         if (Path.DirectorySeparatorChar == '\\')
72                                 RegistryApi = new Win32RegistryApi ();
73                         else
74                                 RegistryApi = new UnixRegistryApi ();
75                 }
76
77                 /// <summary>
78                 ///     Construct an instance of a root registry key entry.
79                 /// </summary>
80                 internal RegistryKey (RegistryHive hiveId) : this (hiveId, 
81                         new IntPtr ((int) hiveId), false)
82                 {
83                 }
84
85                 /// <summary>
86                 ///     Construct an instance of a root registry key entry.
87                 /// </summary>
88                 internal RegistryKey (RegistryHive hiveId, IntPtr keyHandle, bool remoteRoot)
89                 {
90                         hive = hiveId;
91                         handle = keyHandle;
92                         qname = GetHiveName (hiveId);
93                         isRemoteRoot = remoteRoot;
94                         isWritable = true; // always consider root writable
95                 }
96
97                 /// <summary>
98                 ///     Construct an instance of a registry key entry.
99                 /// </summary>
100                 internal RegistryKey (object data, string keyName, bool writable)
101                 {
102                         handle = data;
103                         qname = keyName;
104                         isWritable = writable;
105                 }
106
107                 #region PublicAPI
108
109                 /// <summary>
110                 ///     Dispose of registry key object. Close the 
111                 ///     key if it's still open.
112                 /// </summary>
113 #if NET_4_0
114                 public void Dispose ()
115 #else
116                 void IDisposable.Dispose ()
117 #endif
118                 {
119                         GC.SuppressFinalize (this);
120                         Close ();
121                 }
122
123                 
124                 /// <summary>
125                 ///     Final cleanup of registry key object. Close the 
126                 ///     key if it's still open.
127                 /// </summary>
128                 ~RegistryKey ()
129                 {
130                         Close ();
131                 }
132
133                 
134                 /// <summary>
135                 ///     Get the fully qualified registry key name.
136                 /// </summary>
137                 public string Name {
138                         get { return qname; }
139                 }
140         
141                 
142                 /// <summary>
143                 ///     Flush the current registry state to disk.
144                 /// </summary>
145                 public void Flush()
146                 {
147                         RegistryApi.Flush (this);
148                 }
149                 
150                 
151                 /// <summary>
152                 ///     Close the current registry key and flushes the state of the registry
153                 /// right away.
154                 /// </summary>
155                 public void Close()
156                 {
157                         Flush ();
158
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)
162                                 return;
163                         
164                         RegistryApi.Close (this);
165                         handle = null;
166 #if NET_4_0
167                         safe_handle = null;
168 #endif
169                 }
170                 
171                 
172                 /// <summary>
173                 ///     get the number of sub-keys for this key
174                 /// </summary>
175                 public int SubKeyCount {
176                         get {
177                                 AssertKeyStillValid ();
178
179                                 return RegistryApi.SubKeyCount (this);
180                         }
181                 }
182
183                 
184                 /// <summary>
185                 ///     get the number of values for this key
186                 /// </summary>
187                 public int ValueCount {
188                         get {
189                                 AssertKeyStillValid ();
190
191                                 return RegistryApi.ValueCount (this);
192                         }
193                 }
194
195 #if NET_4_0
196                 [ComVisible (false)]
197                 [MonoTODO ("Not implemented in Unix")]
198                 public SafeRegistryHandle Handle {
199                         get {
200                                 AssertKeyStillValid ();
201
202                                 if (safe_handle == null) {
203                                         IntPtr h = RegistryApi.GetHandle (this);
204                                         safe_handle = new SafeRegistryHandle (h, true);
205                                 }
206
207                                 return safe_handle;
208                         }
209                 }
210
211                 [ComVisible (false)]
212                 [MonoLimitation ("View is ignored in Mono.")]
213                 public RegistryView View {
214                         get {
215                                 return RegistryView.Default;
216                         }
217                 }
218 #endif
219
220                 
221                 /// <summary>
222                 ///     Set a registry value.
223                 /// </summary>
224                 public void SetValue (string name, object value)
225                 {
226                         AssertKeyStillValid ();
227
228                         if (value == null)
229                                 throw new ArgumentNullException ("value");
230
231                         if (name != null)
232                                 AssertKeyNameLength (name);
233
234                         if (!IsWritable)
235                                 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
236
237                         RegistryApi.SetValue (this, name, value);
238                 }
239
240                 [ComVisible (false)]
241                 public void SetValue (string name, object value, RegistryValueKind valueKind)
242                 {
243                         AssertKeyStillValid ();
244                         
245                         if (value == null)
246                                 throw new ArgumentNullException ("value");
247
248                         if (name != null)
249                                 AssertKeyNameLength (name);
250
251                         if (!IsWritable)
252                                 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
253
254                         RegistryApi.SetValue (this, name, value, valueKind);
255                 }
256
257                 /// <summary>
258                 ///     Open the sub key specified, for read access.
259                 /// </summary>
260                 public RegistryKey OpenSubKey (string name)
261                 {
262                         return OpenSubKey (name, false);
263                 }
264
265                 
266                 /// <summary>
267                 ///     Open the sub key specified.
268                 /// </summary>
269                 public RegistryKey OpenSubKey (string name, bool writable)
270                 {
271                         AssertKeyStillValid ();
272
273                         if (name == null)
274                                 throw new ArgumentNullException ("name");
275
276                         AssertKeyNameLength (name);
277
278                         return RegistryApi.OpenSubKey (this, name, writable);
279                 }
280                 
281                 
282                 /// <summary>
283                 ///     Get a registry value.
284                 /// </summary>
285                 public object GetValue (string name)
286                 {
287                         return GetValue (name, null);
288                 }
289
290                 
291                 /// <summary>
292                 ///     Get a registry value.
293                 /// </summary>
294                 public object GetValue (string name, object defaultValue)
295                 {
296                         AssertKeyStillValid ();
297                         
298                         return RegistryApi.GetValue (this, name, defaultValue,
299                                 RegistryValueOptions.None);
300                 }
301
302                 [ComVisible (false)]
303                 public object GetValue (string name, object defaultValue, RegistryValueOptions options)
304                 {
305                         AssertKeyStillValid ();
306
307                         return RegistryApi.GetValue (this, name, defaultValue, options);
308                 }
309
310                 [ComVisible (false)]
311                 public RegistryValueKind GetValueKind (string name)
312                 {
313                         return RegistryApi.GetValueKind (this, name);
314                 }
315
316                 /// <summary>
317                 ///     Create a sub key.
318                 /// </summary>
319                 public RegistryKey CreateSubKey (string subkey)
320                 {
321                         AssertKeyStillValid ();
322                         AssertKeyNameNotNull (subkey);
323                         AssertKeyNameLength (subkey);
324
325                         if (!IsWritable)
326                                 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
327                         return RegistryApi.CreateSubKey (this, subkey);
328                 }
329
330                 [ComVisible (false)]
331                 [MonoLimitation ("permissionCheck is ignored in Mono")]
332                 public RegistryKey CreateSubKey (string subkey, RegistryKeyPermissionCheck permissionCheck)
333                 {
334                         return CreateSubKey (subkey);
335                 }
336
337                 [ComVisible (false)]
338                 [MonoLimitation ("permissionCheck and registrySecurity are ignored in Mono")]
339                 public RegistryKey CreateSubKey (string subkey, RegistryKeyPermissionCheck permissionCheck, RegistrySecurity registrySecurity)
340                 {
341                         return CreateSubKey (subkey);
342                 }
343
344 #if NET_4_0
345                 [ComVisible (false)]
346                 [MonoLimitation ("permissionCheck is ignored in Mono")]
347                 public RegistryKey CreateSubKey (string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions options)
348                 {
349                         AssertKeyStillValid ();
350                         AssertKeyNameNotNull (subkey);
351                         AssertKeyNameLength (subkey);
352
353                         if (!IsWritable)
354                                 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
355
356                         return RegistryApi.CreateSubKey (this, subkey, options);
357                 }
358
359                 [ComVisible (false)]
360                 [MonoLimitation ("permissionCheck and registrySecurity are ignored in Mono")]
361                 public RegistryKey CreateSubKey (string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions,
362                         RegistrySecurity registrySecurity)
363                 {
364                         return CreateSubKey (subkey, permissionCheck, registryOptions);
365                 }
366 #endif
367
368                 
369                 /// <summary>
370                 ///     Delete the specified subkey.
371                 /// </summary>
372                 public void DeleteSubKey(string subkey)
373                 {
374                         DeleteSubKey (subkey, true);
375                 }
376                 
377                 
378                 /// <summary>
379                 ///     Delete the specified subkey.
380                 /// </summary>
381                 public void DeleteSubKey(string subkey, bool throwOnMissingSubKey)
382                 {
383                         AssertKeyStillValid ();
384                         AssertKeyNameNotNull (subkey);
385                         AssertKeyNameLength (subkey);
386
387                         if (!IsWritable)
388                                 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
389
390                         RegistryKey child = OpenSubKey (subkey);
391                         
392                         if (child == null) {
393                                 if (throwOnMissingSubKey)
394                                         throw new ArgumentException ("Cannot delete a subkey tree"
395                                                 + " because the subkey does not exist.");
396                                 return;
397                         }
398
399                         if (child.SubKeyCount > 0){
400                                 throw new InvalidOperationException ("Registry key has subkeys"
401                                         + " and recursive removes are not supported by this method.");
402                         }
403                         
404                         child.Close ();
405
406                         RegistryApi.DeleteKey (this, subkey, throwOnMissingSubKey);
407                 }
408                 
409                 
410                 /// <summary>
411                 ///     Delete a sub tree (node, and values alike).
412                 /// </summary>
413                 public void DeleteSubKeyTree(string subkey)
414                 {
415                         DeleteSubKeyTree (subkey, true);
416                 }
417
418 #if NET_4_0
419                 public
420 #endif
421                 void DeleteSubKeyTree (string subkey, bool throwOnMissingSubKey)
422                 {
423                         // Note: this is done by deleting sub-nodes recursively.
424                         // The preformance is not very good. There may be a 
425                         // better way to implement this.
426                         
427                         AssertKeyStillValid ();
428                         AssertKeyNameNotNull (subkey);
429                         AssertKeyNameLength (subkey);
430                         
431                         RegistryKey child = OpenSubKey (subkey, true);
432                         if (child == null) {
433                                 if (!throwOnMissingSubKey)
434                                         return;
435
436                                 throw new ArgumentException ("Cannot delete a subkey tree"
437                                         + " because the subkey does not exist.");
438                         }
439
440                         child.DeleteChildKeysAndValues ();
441                         child.Close ();
442                         DeleteSubKey (subkey, false);
443                 }
444                 
445
446                 /// <summary>
447                 ///     Delete a value from the registry.
448                 /// </summary>
449                 public void DeleteValue(string name)
450                 {
451                         DeleteValue (name, true);
452                 }
453                 
454                 
455                 /// <summary>
456                 ///     Delete a value from the registry.
457                 /// </summary>
458                 public void DeleteValue(string name, bool throwOnMissingValue)
459                 {
460                         AssertKeyStillValid ();
461
462                         if (name == null)
463                                 throw new ArgumentNullException ("name");
464
465                         if (!IsWritable)
466                                 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
467
468                         RegistryApi.DeleteValue (this, name, throwOnMissingValue);
469                 }
470
471                 public RegistrySecurity GetAccessControl ()
472                 {
473                         throw new NotImplementedException ();
474                 }
475                 
476                 public RegistrySecurity GetAccessControl (AccessControlSections includeSections)
477                 {
478                         throw new NotImplementedException ();
479                 }
480                 
481                 
482                 /// <summary>
483                 ///     Get the names of the sub keys.
484                 /// </summary>
485                 public string[] GetSubKeyNames()
486                 {
487                         AssertKeyStillValid ();
488
489                         return RegistryApi.GetSubKeyNames (this);
490                 }
491                 
492                 
493                 /// <summary>
494                 ///     Get the names of values contained in this key.
495                 /// </summary>
496                 public string[] GetValueNames()
497                 {
498                         AssertKeyStillValid ();
499                         return RegistryApi.GetValueNames (this);
500                 }
501
502 #if NET_4_0
503                 [ComVisible (false)]
504                 [SecurityPermission (SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
505                 [MonoTODO ("Not implemented on unix")]
506                 public static RegistryKey FromHandle (SafeRegistryHandle handle)
507                 {
508                         if (handle == null)
509                                 throw new ArgumentNullException ("handle");
510
511                         return RegistryApi.FromHandle (handle);
512                 }
513
514                 [ComVisible (false)]
515                 [SecurityPermission (SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
516                 [MonoTODO ("Not implemented on unix")]
517                 public static RegistryKey FromHandle (SafeRegistryHandle handle, RegistryView view)
518                 {
519                         return FromHandle (handle);
520                 }
521 #endif
522                 
523                 
524                 [MonoTODO ("Not implemented on unix")]
525                 public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey,string machineName)
526                 {
527                         if (machineName == null)
528                                 throw new ArgumentNullException ("machineName");
529                         return RegistryApi.OpenRemoteBaseKey (hKey, machineName);
530                 }
531
532 #if NET_4_0
533                 [ComVisible (false)]
534                 [MonoTODO ("Not implemented on unix")]
535                 public static RegistryKey OpenRemoteBaseKey (RegistryHive hKey, string machineName, RegistryView view)
536                 {
537                         if (machineName == null)
538                                 throw new ArgumentNullException ("machineName");
539                         return RegistryApi.OpenRemoteBaseKey (hKey, machineName);
540                 }
541
542                 [ComVisible (false)]
543                 [MonoLimitation ("View is ignored in Mono")]
544                 public static RegistryKey OpenBaseKey (RegistryHive hKey, RegistryView view)
545                 {
546                         switch (hKey) {
547                                 case RegistryHive.ClassesRoot:
548                                         return Registry.ClassesRoot;
549                                 case RegistryHive.CurrentConfig:
550                                         return Registry.CurrentConfig;
551                                 case RegistryHive.CurrentUser:
552                                         return Registry.CurrentUser;
553                                 case RegistryHive.DynData:
554                                         return Registry.DynData;
555                                 case RegistryHive.LocalMachine:
556                                         return Registry.LocalMachine;
557                                 case RegistryHive.PerformanceData:
558                                         return Registry.PerformanceData;
559                                 case RegistryHive.Users:
560                                         return Registry.Users;
561                         }
562
563                         throw new ArgumentException ("hKey");
564                 }
565 #endif
566
567                 [ComVisible (false)]
568                 [MonoLimitation ("permissionCheck is ignored in Mono")]
569                 public RegistryKey OpenSubKey (string name, RegistryKeyPermissionCheck permissionCheck)
570                 {
571                         return OpenSubKey (name);
572                 }
573                 
574                 [ComVisible (false)]
575                 [MonoLimitation ("permissionCheck and rights are ignored in Mono")]
576                 public RegistryKey OpenSubKey (string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights)
577                 {
578                         return OpenSubKey (name);
579                 }
580                 
581                 public void SetAccessControl (RegistrySecurity registrySecurity)
582                 {
583                         throw new NotImplementedException ();
584                 }
585                 
586                 
587                 /// <summary>
588                 ///     Build a string representation of the registry key.
589                 ///     Conatins the fully qualified key name, and the Hex
590                 ///     representation of the registry key handle.
591                 /// </summary>
592                 public override string ToString()
593                 {
594                         AssertKeyStillValid ();
595
596                         return RegistryApi.ToString (this);
597                 }
598
599                 #endregion // PublicAPI
600
601                 internal bool IsRoot {
602                         get { return hive != null; }
603                 }
604
605                 private bool IsWritable {
606                         get { return isWritable; }
607                 }
608
609                 internal RegistryHive Hive {
610                         get {
611                                 if (!IsRoot)
612                                         throw new NotSupportedException ();
613                                 return (RegistryHive) hive;
614                         }
615                 }
616
617                 // returns the key handle for the win32 implementation and the
618                 // KeyHandler for the unix implementation
619                 internal object InternalHandle {
620                         get { return handle; }
621                 }
622
623                 /// <summary>
624                 /// validate that the registry key handle is still usable.
625                 /// </summary>
626                 private void AssertKeyStillValid ()
627                 {
628                         if (handle == null)
629                                 throw new ObjectDisposedException ("Microsoft.Win32.RegistryKey");
630                 }
631
632                 
633                 /// <summary>
634                 /// validate that the registry key handle is still usable, and
635                 /// that the 'subKeyName' is not null.
636                 /// </summary>
637                 private void AssertKeyNameNotNull (string subKeyName)
638                 {
639                         if (subKeyName == null)
640                                 throw new ArgumentNullException ("name");
641                 }
642
643                 private void AssertKeyNameLength (string name)
644                 {
645                         if (name.Length > 255)
646                                 throw new ArgumentException ("Name of registry key cannot be greater than 255 characters");
647                 }
648
649                 /// <summary>
650                 ///     Utility method to delelte a key's sub keys and values.
651                 ///     This method removes a level of indirection when deleting
652                 ///     key node trees.
653                 /// </summary>
654                 private void DeleteChildKeysAndValues ()
655                 {
656                         if (IsRoot)
657                                 return;
658                         
659                         string[] subKeys = GetSubKeyNames ();
660                         foreach (string subKey in subKeys)
661                         {
662                                 RegistryKey sub = OpenSubKey (subKey, true);
663                                 sub.DeleteChildKeysAndValues ();
664                                 sub.Close ();
665                                 DeleteSubKey (subKey, false);
666                         }
667
668                         string[] values = GetValueNames ();
669                         foreach (string value in values) {
670                                 DeleteValue (value, false);
671                         }
672                 }
673
674                 /// <summary>
675                 ///     decode a byte array as a string, and strip trailing nulls
676                 /// </summary>
677                 static internal string DecodeString (byte[] data)
678                 {
679                         string stringRep = Encoding.Unicode.GetString (data);
680                         int idx = stringRep.IndexOf ('\0');
681                         if (idx != -1)
682                                 stringRep = stringRep.TrimEnd ('\0');
683                         return stringRep;
684                 }
685
686                 static internal IOException CreateMarkedForDeletionException ()
687                 {
688                         throw new IOException ("Illegal operation attempted on a"
689                                 + " registry key that has been marked for deletion.");
690                 }
691
692                 static string GetHiveName (RegistryHive hive)
693                 {
694                         switch (hive) {
695                         case RegistryHive.ClassesRoot:
696                                 return "HKEY_CLASSES_ROOT";
697                         case RegistryHive.CurrentConfig:
698                                 return "HKEY_CURRENT_CONFIG";
699                         case RegistryHive.CurrentUser:
700                                 return "HKEY_CURRENT_USER";
701                         case RegistryHive.DynData:
702                                 return "HKEY_DYN_DATA";
703                         case RegistryHive.LocalMachine:
704                                 return "HKEY_LOCAL_MACHINE";
705                         case RegistryHive.PerformanceData:
706                                 return "HKEY_PERFORMANCE_DATA";
707                         case RegistryHive.Users:
708                                 return "HKEY_USERS";
709                         }
710
711                         throw new NotImplementedException (string.Format (
712                                 "Registry hive '{0}' is not implemented.", hive.ToString ()));
713                 }
714
715         }
716 }
717
718 #endif // NET_2_1
719