2 // Microsoft.Win32/Win32RegistryApi.cs: wrapper for win32 registry API
5 // Erik LeBel (eriklebel@yahoo.ca)
6 // Jackson Harper (jackson@ximian.com)
7 // Miguel de Icaza (miguel@gnome.org)
9 // Copyright (C) Erik LeBel 2004
10 // (C) 2004, 2005 Novell, Inc (http://www.novell.com)
14 // Copyright (C) 2004, 2005 Novell, Inc (http://www.novell.com)
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 using System.Collections;
38 using System.Runtime.InteropServices;
39 using System.Security;
42 namespace Microsoft.Win32
45 /// Function stubs, constants and helper functions for
46 /// the Win32 registry manipulation utilities.
48 internal class Win32RegistryApi : IRegistryApi
50 // bit masks for registry key open access permissions
51 const int OpenRegKeyRead = 0x00020019;
52 const int OpenRegKeyWrite = 0x00020006;
54 // FIXME must be a way to determin this dynamically?
55 const int Int32ByteSize = 4;
57 // FIXME this is hard coded on Mono, can it be determined dynamically?
58 readonly int NativeBytesPerCharacter = Marshal.SystemDefaultCharSize;
60 internal enum RegistryType {
62 EnvironmentString = 2,
68 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegCreateKey")]
69 static extern int RegCreateKey (IntPtr keyBase, string keyName, out IntPtr keyHandle);
71 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegCloseKey")]
72 static extern int RegCloseKey (IntPtr keyHandle);
74 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegFlushKey")]
75 private static extern int RegFlushKey (IntPtr keyHandle);
77 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegOpenKeyEx")]
78 private static extern int RegOpenKeyEx (IntPtr keyBase,
79 string keyName, IntPtr reserved, int access,
80 out IntPtr keyHandle);
82 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegDeleteKey")]
83 private static extern int RegDeleteKey (IntPtr keyHandle, string valueName);
85 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegDeleteValue")]
86 private static extern int RegDeleteValue (IntPtr keyHandle, string valueName);
88 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegEnumKey")]
89 private static extern int RegEnumKey (IntPtr keyBase, int index, [Out] byte[] nameBuffer, int bufferLength);
91 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegEnumValue")]
92 private static extern int RegEnumValue (IntPtr keyBase,
93 int index, StringBuilder nameBuffer,
94 ref int nameLength, IntPtr reserved,
95 ref RegistryType type, IntPtr data, IntPtr dataLength);
97 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegSetValueEx")]
98 private static extern int RegSetValueEx (IntPtr keyBase,
99 string valueName, IntPtr reserved, RegistryType type,
100 StringBuilder data, int rawDataLength);
102 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegSetValueEx")]
103 private static extern int RegSetValueEx (IntPtr keyBase,
104 string valueName, IntPtr reserved, RegistryType type,
105 string data, int rawDataLength);
107 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegSetValueEx")]
108 private static extern int RegSetValueEx (IntPtr keyBase,
109 string valueName, IntPtr reserved, RegistryType type,
110 byte[] rawData, int rawDataLength);
112 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegSetValueEx")]
113 private static extern int RegSetValueEx (IntPtr keyBase,
114 string valueName, IntPtr reserved, RegistryType type,
115 ref int data, int rawDataLength);
117 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegQueryValueEx")]
118 private static extern int RegQueryValueEx (IntPtr keyBase,
119 string valueName, IntPtr reserved, ref RegistryType type,
120 IntPtr zero, ref int dataSize);
122 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegQueryValueEx")]
123 private static extern int RegQueryValueEx (IntPtr keyBase,
124 string valueName, IntPtr reserved, ref RegistryType type,
125 [Out] byte[] data, ref int dataSize);
127 [DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegQueryValueEx")]
128 private static extern int RegQueryValueEx (IntPtr keyBase,
129 string valueName, IntPtr reserved, ref RegistryType type,
130 ref int data, ref int dataSize);
133 /// Acctually read a registry value. Requires knoledge of the
134 /// value's type and size.
136 public object GetValue (RegistryKey rkey, string name, bool returnDefaultValue, object defaultValue)
138 RegistryType type = 0;
141 IntPtr handle = (IntPtr)rkey.Data;
142 int result = RegQueryValueEx (handle, name, IntPtr.Zero, ref type, IntPtr.Zero, ref size);
144 if (result == Win32ResultCode.FileNotFound) {
145 if (returnDefaultValue) {
151 if (result != Win32ResultCode.MoreData && result != Win32ResultCode.Success ) {
152 GenerateException (result);
155 if (type == RegistryType.String || type == RegistryType.EnvironmentString) {
157 result = GetBinaryValue (rkey, name, type, out data, size);
158 obj = RegistryKey.DecodeString (data);
159 } else if (type == RegistryType.Dword) {
161 result = RegQueryValueEx (handle, name, IntPtr.Zero, ref type, ref data, ref size);
163 } else if (type == RegistryType.Binary) {
165 result = GetBinaryValue (rkey, name, type, out data, size);
167 } else if (type == RegistryType.StringArray) {
170 result = GetBinaryValue (rkey, name, type, out data, size);
172 if (result == Win32ResultCode.Success)
173 obj = RegistryKey.DecodeString (data).Split ('\0');
175 // should never get here
176 throw new SystemException ();
179 // check result codes again:
180 if (result != Win32ResultCode.Success)
182 GenerateException (result);
189 public void SetValue (RegistryKey rkey, string name, object value)
191 Type type = value.GetType ();
193 IntPtr handle = (IntPtr)rkey.Data;
195 if (type == typeof (int)) {
196 int rawValue = (int)value;
197 result = RegSetValueEx (handle, name, IntPtr.Zero, RegistryType.Dword, ref rawValue, Int32ByteSize);
198 } else if (type == typeof (byte[])) {
199 byte[] rawValue = (byte[]) value;
200 result = RegSetValueEx (handle, name, IntPtr.Zero, RegistryType.Binary, rawValue, rawValue.Length);
201 } else if (type == typeof (string[])) {
202 string[] vals = (string[]) value;
203 StringBuilder fullStringValue = new StringBuilder ();
204 foreach (string v in vals)
206 fullStringValue.Append (v);
207 fullStringValue.Append ('\0');
209 fullStringValue.Append ('\0');
211 byte[] rawValue = Encoding.Unicode.GetBytes (fullStringValue.ToString ());
213 result = RegSetValueEx (handle, name, IntPtr.Zero, RegistryType.StringArray, rawValue, rawValue.Length);
214 } else if (type.IsArray) {
215 throw new ArgumentException ("Only string and byte arrays can written as registry values");
217 string rawValue = String.Format ("{0}{1}", value, '\0');
218 result = RegSetValueEx (handle, name, IntPtr.Zero, RegistryType.String, rawValue,
219 rawValue.Length * NativeBytesPerCharacter);
222 // handle the result codes
223 if (result != Win32ResultCode.Success)
225 GenerateException (result);
230 /// Get a binary value.
232 private int GetBinaryValue (RegistryKey rkey, string name, RegistryType type, out byte[] data, int size)
234 byte[] internalData = new byte [size];
235 IntPtr handle = (IntPtr)rkey.Data;
236 int result = RegQueryValueEx (handle, name, IntPtr.Zero, ref type, internalData, ref size);
242 // Arbitrary max size for key/values names that can be fetched.
243 // .NET framework SDK docs say that the max name length that can
244 // be used is 255 characters, we'll allow for a bit more.
245 const int BufferMaxLength = 1024;
247 public int SubKeyCount (RegistryKey rkey)
250 byte[] stringBuffer = new byte [BufferMaxLength];
251 IntPtr handle = (IntPtr)rkey.Data;
253 for (index = 0; true; index ++) {
254 result = RegEnumKey (handle, index, stringBuffer, BufferMaxLength);
256 if (result == Win32ResultCode.Success)
259 if (result == Win32ResultCode.NoMoreEntries)
262 // something is wrong!!
263 GenerateException (result);
268 public int ValueCount (RegistryKey rkey)
270 int index, result, bufferCapacity;
272 StringBuilder buffer = new StringBuilder (BufferMaxLength);
274 IntPtr handle = (IntPtr)rkey.Data;
275 for (index = 0; true; index ++) {
277 bufferCapacity = buffer.Capacity;
278 result = RegEnumValue (handle, index,
279 buffer, ref bufferCapacity,
280 IntPtr.Zero, ref type,
281 IntPtr.Zero, IntPtr.Zero);
283 if (result == Win32ResultCode.Success || result == Win32ResultCode.MoreData)
286 if (result == Win32ResultCode.NoMoreEntries)
289 // something is wrong
290 GenerateException (result);
295 public RegistryKey OpenSubKey (RegistryKey rkey, string keyName, bool writtable)
297 int access = OpenRegKeyRead;
298 if (writtable) access |= OpenRegKeyWrite;
299 IntPtr handle = new IntPtr ((int) rkey.Data);
302 int result = RegOpenKeyEx (handle, keyName, IntPtr.Zero, access, out subKeyHandle);
304 if (result == Win32ResultCode.FileNotFound)
307 if (result != Win32ResultCode.Success)
308 GenerateException (result);
310 return new RegistryKey (subKeyHandle, CombineName (rkey, keyName));
313 public void Flush (RegistryKey rkey)
315 IntPtr handle = (IntPtr)rkey.Data;
316 RegFlushKey (handle);
319 public void Close (RegistryKey rkey)
321 IntPtr handle = (IntPtr)rkey.Data;
322 RegCloseKey (handle);
325 public RegistryKey CreateSubKey (RegistryKey rkey, string keyName)
327 IntPtr handle = (IntPtr)rkey.Data;
329 int result = RegCreateKey (handle , keyName, out subKeyHandle);
331 if (result != Win32ResultCode.Success) {
332 GenerateException (result);
335 RegistryKey subKey = new RegistryKey (subKeyHandle, CombineName (rkey, keyName));
340 public void DeleteKey (RegistryKey rkey, string keyName, bool shouldThrowWhenKeyMissing)
342 IntPtr handle = (IntPtr)rkey.Data;
343 int result = RegDeleteKey (handle, keyName);
345 if (result == Win32ResultCode.FileNotFound) {
346 if (shouldThrowWhenKeyMissing)
347 throw new ArgumentException ("key " + keyName);
351 if (result != Win32ResultCode.Success)
352 GenerateException (result);
355 public void DeleteValue (RegistryKey rkey, string value, bool shouldThrowWhenKeyMissing)
357 IntPtr handle = (IntPtr)rkey.Data;
358 int result = RegDeleteValue (handle, value);
360 if (result == Win32ResultCode.FileNotFound){
361 if (shouldThrowWhenKeyMissing)
362 throw new ArgumentException ("value " + value);
366 if (result != Win32ResultCode.Success)
367 GenerateException (result);
370 public string [] GetSubKeyNames (RegistryKey rkey)
372 IntPtr handle = (IntPtr)rkey.Data;
373 byte[] buffer = new byte [BufferMaxLength];
374 int bufferCapacity = BufferMaxLength;
375 ArrayList keys = new ArrayList ();
377 for (int index = 0; true; index ++) {
378 int result = RegEnumKey (handle, index, buffer, bufferCapacity);
380 if (result == Win32ResultCode.Success) {
381 keys.Add (RegistryKey.DecodeString (buffer));
385 if (result == Win32ResultCode.NoMoreEntries)
388 // should not be here!
389 GenerateException (result);
391 return (string []) keys.ToArray (typeof(String));
395 public string [] GetValueNames (RegistryKey rkey)
397 IntPtr handle = (IntPtr)rkey.Data;
398 ArrayList values = new ArrayList ();
400 for (int index = 0; true; index ++)
402 StringBuilder buffer = new StringBuilder (BufferMaxLength);
403 int bufferCapacity = buffer.Capacity;
404 RegistryType type = 0;
406 int result = RegEnumValue (handle, index, buffer, ref bufferCapacity,
407 IntPtr.Zero, ref type, IntPtr.Zero, IntPtr.Zero);
409 if (result == Win32ResultCode.Success || result == Win32ResultCode.MoreData) {
410 values.Add (buffer.ToString ());
414 if (result == Win32ResultCode.NoMoreEntries)
417 GenerateException (result);
420 return (string []) values.ToArray (typeof(String));
424 /// convert a win32 error code into an appropriate exception.
426 private void GenerateException (int errorCode)
429 case Win32ResultCode.FileNotFound:
430 case Win32ResultCode.InvalidParameter:
431 throw new ArgumentException ();
433 case Win32ResultCode.AccessDenied:
434 throw new SecurityException ();
437 // unidentified system exception
438 throw new SystemException ();
442 public string ToString (RegistryKey rkey)
444 IntPtr handle = (IntPtr)rkey.Data;
446 return String.Format ("{0} [0x{1:X}]", rkey.Name, handle.ToInt32 ());
450 /// utility: Combine the sub key name to the current name to produce a
451 /// fully qualified sub key name.
453 internal static string CombineName (RegistryKey rkey, string localName)
455 return String.Concat (rkey.Name, "\\", localName);