Add tests
[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 using System;
33 using System.IO;
34 using System.Collections;
35 using System.Diagnostics;
36 using System.Runtime.InteropServices;
37 using System.Security;
38 using System.Text;
39
40 namespace Microsoft.Win32
41 {
42         /// <summary>
43         ///     Wrapper class for Windows Registry Entry.
44         /// </summary>
45         public sealed class RegistryKey : MarshalByRefObject, IDisposable 
46         {
47                 //
48                 // This represents the backend data, used when creating the
49                 // RegistryKey object
50                 //
51                 object handle;
52
53                 object hive; // the RegistryHive if the key represents a base key
54                 readonly string qname;  // the fully qualified registry key name
55                 readonly bool isRemoteRoot;     // is an instance of a remote root key?
56                 readonly bool isWritable;       // is the key openen in writable mode
57
58                 static readonly IRegistryApi RegistryApi;
59
60                 static RegistryKey ()
61                 {
62                         if (Path.DirectorySeparatorChar == '\\')
63                                 RegistryApi = new Win32RegistryApi ();
64                         else
65                                 RegistryApi = new UnixRegistryApi ();
66                 }
67
68                 /// <summary>
69                 ///     Construct an instance of a root registry key entry.
70                 /// </summary>
71                 internal RegistryKey (RegistryHive hiveId) : this (hiveId, 
72                         new IntPtr ((int) hiveId), false)
73                 {
74                 }
75
76                 /// <summary>
77                 ///     Construct an instance of a root registry key entry.
78                 /// </summary>
79                 internal RegistryKey (RegistryHive hiveId, IntPtr keyHandle, bool remoteRoot)
80                 {
81                         hive = hiveId;
82                         handle = keyHandle;
83                         qname = GetHiveName (hiveId);
84                         isRemoteRoot = remoteRoot;
85                         isWritable = true; // always consider root writable
86                 }
87
88                 /// <summary>
89                 ///     Construct an instance of a registry key entry.
90                 /// </summary>
91                 internal RegistryKey (object data, string keyName, bool writable)
92                 {
93                         handle = data;
94                         qname = keyName;
95                         isWritable = writable;
96                 }
97
98                 #region PublicAPI
99
100                 /// <summary>
101                 ///     Dispose of registry key object. Close the 
102                 ///     key if it's still open.
103                 /// </summary>
104                 void IDisposable.Dispose ()
105                 {
106                         GC.SuppressFinalize (this);
107                         Close ();
108                 }
109
110                 
111                 /// <summary>
112                 ///     Final cleanup of registry key object. Close the 
113                 ///     key if it's still open.
114                 /// </summary>
115                 ~RegistryKey ()
116                 {
117                         Close ();
118                 }
119
120                 
121                 /// <summary>
122                 ///     Get the fully qualified registry key name.
123                 /// </summary>
124                 public string Name {
125                         get { return qname; }
126                 }
127         
128                 
129                 /// <summary>
130                 ///     Flush the current registry state to disk.
131                 /// </summary>
132                 public void Flush()
133                 {
134                         RegistryApi.Flush (this);
135                 }
136                 
137                 
138                 /// <summary>
139                 ///     Close the current registry key and flushes the state of the registry
140                 /// right away.
141                 /// </summary>
142                 public void Close()
143                 {
144                         Flush ();
145
146                         // a handle to a remote hive must be closed, while one to a local
147                         // hive should not be closed
148                         if (!isRemoteRoot && IsRoot)
149                                 return;
150                         
151                         RegistryApi.Close (this);
152                         handle = null;
153                 }
154                 
155                 
156                 /// <summary>
157                 ///     get the number of sub-keys for this key
158                 /// </summary>
159                 public int SubKeyCount {
160                         get {
161                                 AssertKeyStillValid ();
162
163                                 return RegistryApi.SubKeyCount (this);
164                         }
165                 }
166
167                 
168                 /// <summary>
169                 ///     get the number of values for this key
170                 /// </summary>
171                 public int ValueCount {
172                         get {
173                                 AssertKeyStillValid ();
174
175                                 return RegistryApi.ValueCount (this);
176                         }
177                 }
178
179                 
180                 /// <summary>
181                 ///     Set a registry value.
182                 /// </summary>
183                 public void SetValue (string name, object value)
184                 {
185                         AssertKeyStillValid ();
186
187                         if (value == null)
188                                 throw new ArgumentNullException ("value");
189
190                         if (!IsWritable)
191                                 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
192
193                         RegistryApi.SetValue (this, name, value);
194                 }
195
196 #if NET_2_0
197                 [ComVisible (false)]
198                 public void SetValue (string name, object value, RegistryValueKind valueKind)
199                 {
200                         AssertKeyStillValid ();
201                         
202                         if (value == null)
203                                 throw new ArgumentNullException ();
204
205                         if (!IsWritable)
206                                 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
207
208                         RegistryApi.SetValue (this, name, value, valueKind);
209                 }
210 #endif
211
212                 /// <summary>
213                 ///     Open the sub key specified, for read access.
214                 /// </summary>
215                 public RegistryKey OpenSubKey (string keyName)
216                 {
217                         return OpenSubKey (keyName, false);
218                 }
219
220                 
221                 /// <summary>
222                 ///     Open the sub key specified.
223                 /// </summary>
224                 public RegistryKey OpenSubKey (string keyName, bool writtable)
225                 {
226                         AssertKeyStillValid ();
227                         AssertKeyNameNotNull (keyName);
228
229                         return RegistryApi.OpenSubKey (this, keyName, writtable);
230                 }
231                 
232                 
233                 /// <summary>
234                 ///     Get a registry value.
235                 /// </summary>
236                 public object GetValue (string name)
237                 {
238                         return GetValue (name, null);
239                 }
240
241                 
242                 /// <summary>
243                 ///     Get a registry value.
244                 /// </summary>
245                 public object GetValue (string name, object defaultValue)
246                 {
247                         AssertKeyStillValid ();
248                         
249                         return RegistryApi.GetValue (this, name, defaultValue,
250                                 RegistryValueOptions.None);
251                 }
252
253 #if NET_2_0
254                 [ComVisible (false)]
255                 public object GetValue (string name, object defaultValue, RegistryValueOptions options)
256                 {
257                         AssertKeyStillValid ();
258
259                         return RegistryApi.GetValue (this, name, defaultValue, options);
260                 }
261 #endif
262
263                 /// <summary>
264                 ///     Create a sub key.
265                 /// </summary>
266                 public RegistryKey CreateSubKey (string subkey)
267                 {
268                         AssertKeyStillValid ();
269                         AssertKeyNameNotNull (subkey);
270                         if (subkey.Length > 255)
271                                 throw new ArgumentException ("keyName length is larger than 255 characters", subkey);
272
273                         if (!IsWritable)
274                                 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
275                         return RegistryApi.CreateSubKey (this, subkey);
276                 }
277                 
278                 
279                 /// <summary>
280                 ///     Delete the specified subkey.
281                 /// </summary>
282                 public void DeleteSubKey(string subkey)
283                 {
284                         DeleteSubKey (subkey, true);
285                 }
286                 
287                 
288                 /// <summary>
289                 ///     Delete the specified subkey.
290                 /// </summary>
291                 public void DeleteSubKey(string subkey, bool throwOnMissingSubKey)
292                 {
293                         AssertKeyStillValid ();
294                         AssertKeyNameNotNull (subkey);
295
296                         if (!IsWritable)
297                                 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
298
299                         RegistryKey child = OpenSubKey (subkey);
300                         
301                         if (child == null) {
302                                 if (throwOnMissingSubKey)
303                                         throw new ArgumentException ("Cannot delete a subkey tree"
304                                                 + " because the subkey does not exist.");
305                                 return;
306                         }
307
308                         if (child.SubKeyCount > 0){
309                                 throw new InvalidOperationException ("Registry key has subkeys"
310                                         + " and recursive removes are not supported by this method.");
311                         }
312                         
313                         child.Close ();
314
315                         RegistryApi.DeleteKey (this, subkey, throwOnMissingSubKey);
316                 }
317                 
318                 
319                 /// <summary>
320                 ///     Delete a sub tree (node, and values alike).
321                 /// </summary>
322                 public void DeleteSubKeyTree(string keyName)
323                 {
324                         // Note: this is done by deleting sub-nodes recursively.
325                         // The preformance is not very good. There may be a 
326                         // better way to implement this.
327                         
328                         AssertKeyStillValid ();
329                         AssertKeyNameNotNull (keyName);
330                         
331                         RegistryKey child = OpenSubKey (keyName, true);
332                         if (child == null)
333                                 throw new ArgumentException ("Cannot delete a subkey tree"
334                                         + " because the subkey does not exist.");
335
336                         child.DeleteChildKeysAndValues ();
337                         child.Close ();
338                         DeleteSubKey (keyName, false);
339                 }
340                 
341
342                 /// <summary>
343                 ///     Delete a value from the registry.
344                 /// </summary>
345                 public void DeleteValue(string value)
346                 {
347                         DeleteValue (value, true);
348                 }
349                 
350                 
351                 /// <summary>
352                 ///     Delete a value from the registry.
353                 /// </summary>
354                 public void DeleteValue(string value, bool shouldThrowWhenKeyMissing)
355                 {
356                         AssertKeyStillValid ();
357                         AssertKeyNameNotNull (value);
358
359                         if (!IsWritable)
360                                 throw new UnauthorizedAccessException ("Cannot write to the registry key.");
361
362                         RegistryApi.DeleteValue (this, value, shouldThrowWhenKeyMissing);
363                 }
364                 
365                 
366                 /// <summary>
367                 ///     Get the names of the sub keys.
368                 /// </summary>
369                 public string[] GetSubKeyNames()
370                 {
371                         AssertKeyStillValid ();
372
373                         return RegistryApi.GetSubKeyNames (this);
374                 }
375                 
376                 
377                 /// <summary>
378                 ///     Get the names of values contained in this key.
379                 /// </summary>
380                 public string[] GetValueNames()
381                 {
382                         AssertKeyStillValid ();
383                         return RegistryApi.GetValueNames (this);
384                 }
385                 
386                 
387                 [MonoTODO ("Not implemented on unix")]
388                 public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey,string machineName)
389                 {
390                         if (machineName == null)
391                                 throw new ArgumentNullException ("machineName");
392                         return RegistryApi.OpenRemoteBaseKey (hKey, machineName);
393                 }
394                 
395                 
396                 /// <summary>
397                 ///     Build a string representation of the registry key.
398                 ///     Conatins the fully qualified key name, and the Hex
399                 ///     representation of the registry key handle.
400                 /// </summary>
401                 public override string ToString()
402                 {
403                         AssertKeyStillValid ();
404
405                         return RegistryApi.ToString (this);
406                 }
407
408                 #endregion // PublicAPI
409
410                 internal bool IsRoot {
411                         get { return hive != null; }
412                 }
413
414                 private bool IsWritable {
415                         get { return isWritable; }
416                 }
417
418                 internal RegistryHive Hive {
419                         get {
420                                 if (!IsRoot)
421                                         throw new NotSupportedException ();
422                                 return (RegistryHive) hive;
423                         }
424                 }
425
426                 // returns the key handle for the win32 implementation and the
427                 // KeyHandler for the unix implementation
428                 internal object Handle {
429                         get { return handle; }
430                 }
431
432                 /// <summary>
433                 /// validate that the registry key handle is still usable.
434                 /// </summary>
435                 private void AssertKeyStillValid ()
436                 {
437                         if (handle == null)
438                                 throw new ObjectDisposedException ("Microsoft.Win32.RegistryKey");
439                 }
440
441                 
442                 /// <summary>
443                 /// validate that the registry key handle is still usable, and
444                 /// that the 'subKeyName' is not null.
445                 /// </summary>
446                 private void AssertKeyNameNotNull (string subKeyName)
447                 {
448                         if (subKeyName == null)
449                                 throw new ArgumentNullException ();
450                 }
451                 
452
453                 /// <summary>
454                 ///     Utility method to delelte a key's sub keys and values.
455                 ///     This method removes a level of indirection when deleting
456                 ///     key node trees.
457                 /// </summary>
458                 private void DeleteChildKeysAndValues ()
459                 {
460                         if (IsRoot)
461                                 return;
462                         
463                         string[] subKeys = GetSubKeyNames ();
464                         foreach (string subKey in subKeys)
465                         {
466                                 RegistryKey sub = OpenSubKey (subKey, true);
467                                 sub.DeleteChildKeysAndValues ();
468                                 sub.Close ();
469                                 DeleteSubKey (subKey, false);
470                         }
471
472                         string[] values = GetValueNames ();
473                         foreach (string value in values) {
474                                 DeleteValue (value, false);
475                         }
476                 }
477
478                 /// <summary>
479                 ///     decode a byte array as a string, and strip trailing nulls
480                 /// </summary>
481                 static internal string DecodeString (byte[] data)
482                 {
483                         string stringRep = Encoding.Unicode.GetString (data);
484                         int idx = stringRep.IndexOf ('\0');
485                         if (idx != -1)
486                                 stringRep = stringRep.TrimEnd ('\0');
487                         return stringRep;
488                 }
489
490                 static internal IOException CreateMarkedForDeletionException ()
491                 {
492                         throw new IOException ("Illegal operation attempted on a"
493                                 + " registry key that has been marked for deletion.");
494                 }
495
496                 static string GetHiveName (RegistryHive hive)
497                 {
498                         switch (hive) {
499                         case RegistryHive.ClassesRoot:
500                                 return "HKEY_CLASSES_ROOT";
501                         case RegistryHive.CurrentConfig:
502                                 return "HKEY_CURRENT_CONFIG";
503                         case RegistryHive.CurrentUser:
504                                 return "HKEY_CURRENT_USER";
505                         case RegistryHive.DynData:
506                                 return "HKEY_DYN_DATA";
507                         case RegistryHive.LocalMachine:
508                                 return "HKEY_LOCAL_MACHINE";
509                         case RegistryHive.PerformanceData:
510                                 return "HKEY_PERFORMANCE_DATA";
511                         case RegistryHive.Users:
512                                 return "HKEY_USERS";
513                         }
514
515                         throw new NotImplementedException (string.Format (
516                                 "Registry hive '{0}' is not implemented.", hive.ToString ()));
517                 }
518
519         }
520 }
521