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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//
// NOTE: A vast majority of this code was copied from BCL in
// ndp\clr\src\BCL\Microsoft\Win32\RegistryKey.cs.
// Namespace: Microsoft.Win32
//
/*
  Note on transaction support:
  Eventually we will want to add support for NT's transactions to our
  TransactedRegistryKey API's (possibly Whidbey M3?).  When we do this, here's
  the list of API's we need to make transaction-aware:

  RegCreateKeyEx
  RegDeleteKey
  RegDeleteValue
  RegEnumKeyEx
  RegEnumValue
  RegOpenKeyEx
  RegQueryInfoKey
  RegQueryValueEx
  RegSetValueEx

  We can ignore RegConnectRegistry (remote registry access doesn't yet have
  transaction support) and RegFlushKey.  RegCloseKey doesn't require any
  additional work.  .
 */

/*
  Note on ACL support:
  The key thing to note about ACL's is you set them on a kernel object like a
  registry key, then the ACL only gets checked when you construct handles to
  them.  So if you set an ACL to deny read access to yourself, you'll still be
  able to read with that handle, but not with new handles.

  Another peculiarity is a Terminal Server app compatibility hack.  The OS
  will second guess your attempt to open a handle sometimes.  If a certain
  combination of Terminal Server app compat registry keys are set, then the
  OS will try to reopen your handle with lesser permissions if you couldn't
  open it in the specified mode.  So on some machines, we will see handles that
  may not be able to read or write to a registry key.  It's very strange.  But
  the real test of these handles is attempting to read or set a value in an
  affected registry key.

  For reference, at least two registry keys must be set to particular values
  for this behavior:
  HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\RegistryExtensionFlags, the least significant bit must be 1.
  HKLM\SYSTEM\CurrentControlSet\Control\TerminalServer\TSAppCompat must be 1
  There might possibly be an interaction with yet a third registry key as well.

*/

using BCLDebug = System.Diagnostics.Debug;

namespace Microsoft.PowerShell.Commands.Internal
{
    using System;
    using System.Collections.Generic;
    using System.Security;
    using System.Security.AccessControl;
    using System.Security.Permissions;
    using System.Text;
    using System.IO;
    using System.Runtime.InteropServices;
    using Microsoft.Win32;
    using System.Runtime.Versioning;
    using System.Globalization;
    using System.Transactions;
    using System.Diagnostics.CodeAnalysis;

    // Putting this in a separate internal class to avoid OACR warning DoNotDeclareReadOnlyMutableReferenceTypes.
    internal sealed class BaseRegistryKeys
    {
        // We could use const here, if C# supported ELEMENT_TYPE_I fully.
        internal static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000));
        internal static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001));
        internal static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002));
        internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003));
        internal static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005));
    }

    /// <summary>
    /// Registry encapsulation. To get an instance of a TransactedRegistryKey use the
    /// Registry class's static members then call OpenSubKey.
    ///
    /// @see Registry
    /// @security(checkDllCalls=off)
    /// @security(checkClassLinking=on)
    /// </summary>
    [ComVisible(true)]
    // Suppressed because these objects are written to the pipeline so need to be accessible.
    [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")]
    public sealed class TransactedRegistryKey : MarshalByRefObject, IDisposable
    {
        private const string resBaseName = "RegistryProviderStrings";

        // Dirty indicates that we have munged data that should be potentially
        // written to disk.
        //
        private const int STATE_DIRTY = 0x0001;

        // SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened"
        // or "closed".
        //
        private const int STATE_SYSTEMKEY = 0x0002;

        // Access
        //
        private const int STATE_WRITEACCESS = 0x0004;

        // Names of keys.  This array must be in the same order as the HKEY values listed above.
        //
        private static readonly string[] s_hkeyNames = new string[] {
                "HKEY_CLASSES_ROOT",
                "HKEY_CURRENT_USER",
                "HKEY_LOCAL_MACHINE",
                "HKEY_USERS",
                "HKEY_PERFORMANCE_DATA",
                "HKEY_CURRENT_CONFIG",
                "HKEY_DYN_DATA"
                };

        // MSDN defines the following limits for registry key names & values:
        // Key Name: 255 characters
        // Value name:  Win9x: 255 NT: 16,383 Unicode characters, or 260 ANSI chars
        // Value: either 1 MB or current available memory, depending on registry format.
        private const int MaxKeyLength = 255;
        private const int MaxValueNameLength = 16383;
        private const int MaxValueDataLength = 1024 * 1024;

        private SafeRegistryHandle _hkey = null;
        private int _state = 0;
        private string _keyName;
        private RegistryKeyPermissionCheck _checkMode;
        private System.Transactions.Transaction _myTransaction;
        private SafeTransactionHandle _myTransactionHandle;

        // This is a wrapper around RegOpenKeyTransacted that implements a workaround
        // to TxF bug number 181242 After calling RegOpenKeyTransacted, it calls RegQueryInfoKey.
        // If that call fails with ERROR_INVALID_TRANSACTION, we have possibly run into bug 181242. To workaround
        // this, we open the key without a transaction and then open it again with
        // a transaction and return THAT hkey.
        private int RegOpenKeyTransactedWrapper(SafeRegistryHandle hKey, string lpSubKey,
                    int ulOptions, int samDesired, out SafeRegistryHandle hkResult,
                    SafeTransactionHandle hTransaction, IntPtr pExtendedParameter)
        {
            int error = Win32Native.ERROR_SUCCESS;
            SafeRegistryHandle hKeyToReturn = null;

            error = Win32Native.RegOpenKeyTransacted(_hkey, lpSubKey, ulOptions, samDesired, out hKeyToReturn, hTransaction, pExtendedParameter);

            if (Win32Native.ERROR_SUCCESS == error && !hKeyToReturn.IsInvalid)
            {
                // This is a check and workaround for TxR bug 181242. If we try to use the transacted hKey we just opened
                // for a call to RegQueryInfoKey and get back a ERROR_INVALID_TRANSACTION error, then the key might be a symbolic link and TxR didn't
                // do the open correctly. The workaround is to open it non-transacted, then open it again transacted without
                // a subkey string. If we get some error other than ERROR_INVALID_TRANSACTION from RegQueryInfoKey, just ignore it for now.
                int subkeyCount = 0;
                int valueCount = 0;
                error = Win32Native.RegQueryInfoKey(hKeyToReturn,
                                          null,
                                          null,
                                          Win32Native.NULL,
                                          ref subkeyCount,  // subkeys
                                          null,
                                          null,
                                          ref valueCount,     // values
                                          null,
                                          null,
                                          null,
                                          null);
                if (Win32Native.ERROR_INVALID_TRANSACTION == error)
                {
                    SafeRegistryHandle nonTxKey = null;
                    SafeRegistryHandle txKey = null;
                    error = Win32Native.RegOpenKeyEx(_hkey, lpSubKey, ulOptions, samDesired, out nonTxKey);
                    // If we got some error on this open, just ignore it and continue on with the handle
                    // we got on the original RegOpenKeyTransacted.
                    if (Win32Native.ERROR_SUCCESS == error)
                    {
                        // Now do an RegOpenKeyTransacted with the non-transacted key and no "subKey" parameter.
                        error = Win32Native.RegOpenKeyTransacted(nonTxKey, null, ulOptions, samDesired, out txKey, hTransaction, pExtendedParameter);
                        if (Win32Native.ERROR_SUCCESS == error)
                        {
                            // Let's use this hkey instead.
                            hKeyToReturn.Dispose();
                            hKeyToReturn = txKey;
                        }

                        nonTxKey.Dispose();
                        nonTxKey = null;
                    }
                }
            }

            hkResult = hKeyToReturn;
            return error;
        }

        /**
         * Creates a TransactedRegistryKey.
         *
         * This key is bound to hkey, if writable is <b>false</b> then no write operations
         * will be allowed. If systemkey is set then the hkey won't be released
         * when the object is GC'ed.
         */
        private TransactedRegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey,
                                      System.Transactions.Transaction transaction, SafeTransactionHandle txHandle)
        {
            _hkey = hkey;
            _keyName = string.Empty;
            if (systemkey)
            {
                _state |= STATE_SYSTEMKEY;
            }

            if (writable)
            {
                _state |= STATE_WRITEACCESS;
            }
            // We want to take our own clone so we can dispose it when we want and
            // aren't susceptible to the caller disposing it.
            if (transaction != null)
            {
                _myTransaction = transaction.Clone();
                _myTransactionHandle = txHandle;
            }
            else
            {
                _myTransaction = null;
                _myTransactionHandle = null;
            }
        }

        private SafeTransactionHandle GetTransactionHandle()
        {
            SafeTransactionHandle safeTransactionHandle = null;

            // If myTransaction is not null and is not the same as Transaction.Current
            // this is an invalid operation. The transaction within which the RegistryKey object was created
            // needs to be the same as the transaction being used now.
            if (_myTransaction != null)
            {
                if (!_myTransaction.Equals(Transaction.Current))
                {
                    throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_MustUseSameTransaction);
                }
                else
                {
                    safeTransactionHandle = _myTransactionHandle;
                }
            }
            else  // we want to use Transaction.Current for the transaction.
            {
                safeTransactionHandle = SafeTransactionHandle.Create();
            }

            return safeTransactionHandle;
        }

        /// <summary>TransactedRegistryKey.Close
        /// <para>Closes this key, flushes it to disk if the contents have been modified.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        public void Close()
        {
            Dispose(true);
        }

        private void Dispose(bool disposing)
        {
            if (_hkey != null)
            {
                if (!IsSystemKey())
                {
                    try
                    {
                        _hkey.Dispose();
                    }
                    catch (IOException)
                    {
                        // we don't really care if the handle is invalid at this point
                    }
                    finally
                    {
                        _hkey = null;
                    }
                }
            }

            if (_myTransaction != null)
            {
                // Dispose the transaction because we cloned it.
                try
                {
                    _myTransaction.Dispose();
                }
                catch (TransactionException)
                {
                    // ignore.
                }
                finally
                {
                    _myTransaction = null;
                }
            }
        }

        /// <summary>TransactedRegistryKey.Flush
        /// <para>Flushes this key. Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        public void Flush()
        {
            // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction.
            VerifyTransaction();
            if (_hkey != null)
            {
                if (IsDirty())
                {
                    int ret = Win32Native.RegFlushKey(_hkey);
                    if (Win32Native.ERROR_SUCCESS != ret)
                    {
                        throw new IOException(Win32Native.GetMessage(ret), ret);
                    }
                }
            }
        }

        /// <summary>TransactedRegistryKey.Dispose
        /// <para>Disposes this key. Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }

        /// <summary>
        /// <para>Creates a new subkey, or opens an existing one.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <param name='subkey'>Name or path to subkey to create or open. Cannot be null or an empty string,
        /// otherwise an ArgumentException is thrown.</param>
        /// <returns>A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current.
        /// returns null if the operation failed.</returns>
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        public TransactedRegistryKey CreateSubKey(string subkey)
        {
            return CreateSubKey(subkey, _checkMode);
        }

        /// <summary>
        /// <para>Creates a new subkey, or opens an existing one.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current.
        /// returns null if the operation failed.</returns>
        /// <param name='subkey'>Name or path to subkey to create or open. Cannot be null or an empty string,
        /// otherwise an ArgumentException is thrown.</param>
        /// <param name='permissionCheck'>One of the Microsoft.Win32.RegistryKeyPermissionCheck values that
        /// specifies whether the key is opened for read or read/write access.</param>
        [ComVisible(false)]
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        public TransactedRegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck)
        {
            return CreateSubKeyInternal(subkey, permissionCheck, (TransactedRegistrySecurity)null);
        }

        /// <summary>
        /// <para>Creates a new subkey, or opens an existing one.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current.
        /// returns null if the operation failed.</returns>
        /// <param name='subkey'>Name or path to subkey to create or open. Cannot be null or an empty string,
        /// otherwise an ArgumentException is thrown.</param>
        /// <param name='permissionCheck'>One of the Microsoft.Win32.RegistryKeyPermissionCheck values that
        /// specifies whether the key is opened for read or read/write access.</param>
        /// <param name='registrySecurity'>A TransactedRegistrySecurity object that specifies the access control security for the new key.</param>
        [ComVisible(false)]
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        public unsafe TransactedRegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, TransactedRegistrySecurity registrySecurity)
        {
            return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity);
        }

        [ComVisible(false)]
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        private unsafe TransactedRegistryKey CreateSubKeyInternal(string subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj)
        {
            ValidateKeyName(subkey);
            // RegCreateKeyTransacted requires a non-empty key name, so let's deal with that here.
            if (string.Empty == subkey)
            {
                throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrEmpty);
            }

            ValidateKeyMode(permissionCheck);
            EnsureWriteable();
            subkey = FixupName(subkey); // Fixup multiple slashes to a single slash

            // only keys opened under read mode is not writable
            TransactedRegistryKey existingKey = InternalOpenSubKey(subkey, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree));
            if (existingKey != null)
            { // Key already exits
                CheckSubKeyWritePermission(subkey);
                CheckSubTreePermission(subkey, permissionCheck);
                existingKey._checkMode = permissionCheck;
                return existingKey;
            }

            CheckSubKeyCreatePermission(subkey);

            Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
            TransactedRegistrySecurity registrySecurity = registrySecurityObj as TransactedRegistrySecurity;
            // For ACL's, get the security descriptor from the RegistrySecurity.
            if (registrySecurity != null)
            {
                secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);

                byte[] sd = registrySecurity.GetSecurityDescriptorBinaryForm();
                // We allocate memory on the stack to improve the speed.
                // So this part of code can't be refactored into a method.
                byte* pSecDescriptor = stackalloc byte[sd.Length];
                Microsoft.PowerShell.Commands.Internal.Buffer.memcpy(sd, 0, pSecDescriptor, 0, sd.Length);
                secAttrs.pSecurityDescriptor = pSecDescriptor;
            }

            int disposition = 0;

            // By default, the new key will be writable.
            SafeRegistryHandle result = null;
            int ret = 0;
            SafeTransactionHandle safeTransactionHandle = GetTransactionHandle();

            ret = Win32Native.RegCreateKeyTransacted(_hkey,
                subkey,
                0,
                null,
                0,
                GetRegistryKeyAccess(permissionCheck != RegistryKeyPermissionCheck.ReadSubTree),
                secAttrs,
                out result,
                out disposition,
                safeTransactionHandle,
                IntPtr.Zero
                );

            if (ret == 0 && !result.IsInvalid)
            {
                TransactedRegistryKey key = new TransactedRegistryKey(result, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), false,
                                                                      Transaction.Current, safeTransactionHandle);
                CheckSubTreePermission(subkey, permissionCheck);
                key._checkMode = permissionCheck;

                if (subkey.Length == 0)
                    key._keyName = _keyName;
                else
                    key._keyName = _keyName + "\\" + subkey;
                return key;
            }
            else if (ret != 0) // syscall failed, ret is an error code.
                Win32Error(ret, _keyName + "\\" + subkey);  // Access denied?

            BCLDebug.Assert(false, "Unexpected code path in RegistryKey::CreateSubKey");
            return null;
        }

        /// <summary>
        /// <para>Deletes the specified subkey. Will throw an exception if the subkey has
        /// subkeys. To delete a tree of subkeys use, DeleteSubKeyTree.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// <exception cref="InvalidOperationException">Thrown if the subkey as child subkeys.</exception>
        /// </summary>
        /// <param name='subkey'>The subkey to delete.</param>
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        public void DeleteSubKey(string subkey)
        {
            DeleteSubKey(subkey, true);
        }

        /// <summary>
        /// <para>Deletes the specified subkey. Will throw an exception if the subkey has
        /// subkeys. To delete a tree of subkeys use, DeleteSubKeyTree.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// <exception cref="InvalidOperationException">Thrown if the subkey as child subkeys.</exception>
        /// <exception cref="ArgumentException">Thrown if true is specified for throwOnMissingSubKey and the
        /// specified subkey does not exist.</exception>
        /// </summary>
        /// <param name='subkey'>The subkey to delete.</param>
        /// <param name='throwOnMissingSubKey'>Specify true if an ArgumentException should be thrown if
        /// the specified subkey does not exist. If false is specified, a missing subkey does not throw
        /// an exception.</param>
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        public void DeleteSubKey(string subkey, bool throwOnMissingSubKey)
        {
            ValidateKeyName(subkey);
            EnsureWriteable();
            subkey = FixupName(subkey); // Fixup multiple slashes to a single slash
            CheckSubKeyWritePermission(subkey);

            // Open the key we are deleting and check for children. Be sure to
            // explicitly call close to avoid keeping an extra HKEY open.
            //
            TransactedRegistryKey key = InternalOpenSubKey(subkey, false);
            if (key != null)
            {
                try
                {
                    if (key.InternalSubKeyCount() > 0)
                    {
                        throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_RegRemoveSubKey);
                    }
                }
                finally
                {
                    key.Close();
                }

                int ret = 0;

                SafeTransactionHandle safeTransactionHandle = GetTransactionHandle();
                ret = Win32Native.RegDeleteKeyTransacted(_hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero);

                if (ret != 0)
                {
                    if (ret == Win32Native.ERROR_FILE_NOT_FOUND)
                    {
                        if (throwOnMissingSubKey)
                        {
                            throw new ArgumentException(RegistryProviderStrings.ArgumentException_RegSubKeyAbsent);
                        }
                    }
                    else
                        Win32Error(ret, null);
                }
            }
            else
            { // there is no key which also means there is no subkey
                if (throwOnMissingSubKey)
                    throw new ArgumentException(RegistryProviderStrings.ArgumentException_RegSubKeyAbsent);
            }
        }

        /// <summary>
        /// <para>Recursively deletes a subkey and any child subkeys.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <param name="subkey">The subkey to delete.</param>
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        public void DeleteSubKeyTree(string subkey)
        {
            ValidateKeyName(subkey);

            // Security concern: Deleting a hive's "" subkey would delete all
            // of that hive's contents.  Don't allow "".
            if ((string.IsNullOrEmpty(subkey) || subkey.Length == 0) && IsSystemKey())
            {
                throw new ArgumentException(RegistryProviderStrings.ArgRegKeyDelHive);
            }

            EnsureWriteable();

            int ret = 0;

            SafeTransactionHandle safeTransactionHandle = GetTransactionHandle();
            subkey = FixupName(subkey); // Fixup multiple slashes to a single slash
            CheckSubTreeWritePermission(subkey);

            TransactedRegistryKey key = InternalOpenSubKey(subkey, true);
            if (key != null)
            {
                try
                {
                    if (key.InternalSubKeyCount() > 0)
                    {
                        string[] keys = key.InternalGetSubKeyNames();

                        for (int i = 0; i < keys.Length; i++)
                        {
                            key.DeleteSubKeyTreeInternal(keys[i]);
                        }
                    }
                }
                finally
                {
                    key.Close();
                }

                ret = Win32Native.RegDeleteKeyTransacted(_hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero);
                if (ret != 0)
                {
                    Win32Error(ret, null);
                }
            }
            else
            {
                throw new ArgumentException(RegistryProviderStrings.Arg_RegSubKeyAbsent);
            }
        }

        // An internal version which does no security checks or argument checking.  Skipping the
        // security checks should give us a slight perf gain on large trees.
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        private void DeleteSubKeyTreeInternal(string subkey)
        {
            int ret = 0;

            SafeTransactionHandle safeTransactionHandle = GetTransactionHandle();
            TransactedRegistryKey key = InternalOpenSubKey(subkey, true);
            if (key != null)
            {
                try
                {
                    if (key.InternalSubKeyCount() > 0)
                    {
                        string[] keys = key.InternalGetSubKeyNames();

                        for (int i = 0; i < keys.Length; i++)
                        {
                            key.DeleteSubKeyTreeInternal(keys[i]);
                        }
                    }
                }
                finally
                {
                    key.Close();
                }

                ret = Win32Native.RegDeleteKeyTransacted(_hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero);
                if (ret != 0)
                {
                    Win32Error(ret, null);
                }
            }
            else
            {
                throw new ArgumentException(RegistryProviderStrings.Arg_RegSubKeyAbsent);
            }
        }

        /// <summary>
        /// <para>Deletes the specified value from this key.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <param name="name">Name of the value to delete.</param>
        public void DeleteValue(string name)
        {
            DeleteValue(name, true);
        }

        /// <summary>
        /// <para>Deletes the specified value from this key.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <param name="name">Name of the value to delete.</param>
        /// <param name="throwOnMissingValue">Specify true if an ArgumentException should be thrown if
        /// the specified value does not exist. If false is specified, a missing value does not throw
        /// an exception.</param>
        public void DeleteValue(string name, bool throwOnMissingValue)
        {
            EnsureWriteable();
            CheckValueWritePermission(name);
            // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction.
            VerifyTransaction();
            int errorCode = Win32Native.RegDeleteValue(_hkey, name);

            //
            // From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE
            // This still means the name doesn't exist. We need to be consistent with previous OS.
            //
            if (errorCode == Win32Native.ERROR_FILE_NOT_FOUND || errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE)
            {
                if (throwOnMissingValue)
                {
                    throw new ArgumentException(RegistryProviderStrings.Arg_RegSubKeyValueAbsent);
                }
                else
                {
                    errorCode = Win32Native.ERROR_SUCCESS;
                }
            }

            if (Win32Native.ERROR_SUCCESS != errorCode)
            {
                Win32Error(errorCode, null);
            }
        }

        /**
         * Retrieves a new TransactedRegistryKey that represents the requested key. Valid
         * values are:
         *
         * HKEY_CLASSES_ROOT,
         * HKEY_CURRENT_USER,
         * HKEY_LOCAL_MACHINE,
         * HKEY_USERS,
         * HKEY_PERFORMANCE_DATA,
         * HKEY_CURRENT_CONFIG,
         * HKEY_DYN_DATA.
         *
         * @param hKey HKEY_* to open.
         *
         * @return the TransactedRegistryKey requested.
         */
        internal static TransactedRegistryKey GetBaseKey(IntPtr hKey)
        {
            int index = ((int)hKey) & 0x0FFFFFFF;
            BCLDebug.Assert(index >= 0 && index < s_hkeyNames.Length, "index is out of range!");
            BCLDebug.Assert((((int)hKey) & 0xFFFFFFF0) == 0x80000000, "Invalid hkey value!");

            SafeRegistryHandle srh = new SafeRegistryHandle(hKey, false);

            // For Base keys, there is no transaction associated with the HKEY.
            TransactedRegistryKey key = new TransactedRegistryKey(srh, true, true, null, null);
            key._checkMode = RegistryKeyPermissionCheck.Default;
            key._keyName = s_hkeyNames[index];
            return key;
        }

        /// <summary>
        /// <para>Retrieves a subkey. If readonly is true, then the subkey is opened with
        /// read-only access.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>The subkey requested or null if the operation failed.</returns>
        /// <param name="name">Name or path of the subkey to open.</param>
        /// <param name="writable">Set to true of you only need readonly access.</param>
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        public TransactedRegistryKey OpenSubKey(string name, bool writable)
        {
            ValidateKeyName(name);
            EnsureNotDisposed();
            name = FixupName(name); // Fixup multiple slashes to a single slash

            CheckOpenSubKeyPermission(name, writable);
            SafeRegistryHandle result = null;
            int ret = 0;
            SafeTransactionHandle safeTransactionHandle = GetTransactionHandle();

            ret = RegOpenKeyTransactedWrapper(_hkey, name, 0, GetRegistryKeyAccess(writable), out result, safeTransactionHandle, IntPtr.Zero);

            if (ret == 0 && !result.IsInvalid)
            {
                TransactedRegistryKey key = new TransactedRegistryKey(result, writable, false, Transaction.Current, safeTransactionHandle);
                key._checkMode = GetSubKeyPermissionCheck(writable);
                key._keyName = _keyName + "\\" + name;
                return key;
            }

            // Return null if we didn't find the key.
            if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL)
            {
                // We need to throw SecurityException here for compatibility reasons,
                // although UnauthorizedAccessException will make more sense.
                throw new SecurityException(RegistryProviderStrings.Security_RegistryPermission);
            }

            return null;
        }

        /// <summary>
        /// <para>Retrieves a subkey.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>The subkey requested or null if the operation failed.</returns>
        /// <param name="name">Name or path of the subkey to open.</param>
        /// <param name="permissionCheck">One of the Microsoft.Win32.RegistryKeyPermissionCheck values that specifies
        /// whether the key is opened for read or read/write access.</param>
        [ComVisible(false)]
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        public TransactedRegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck)
        {
            ValidateKeyMode(permissionCheck);
            return InternalOpenSubKey(name, permissionCheck, GetRegistryKeyAccess(permissionCheck));
        }

        /// <summary>
        /// <para>Retrieves a subkey.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>The subkey requested or null if the operation failed.</returns>
        /// <param name="name">Name or path of the subkey to open.</param>
        /// <param name="permissionCheck">One of the Microsoft.Win32.RegistryKeyPermissionCheck values that specifies
        /// whether the key is opened for read or read/write access.</param>
        /// <param name="rights">A bitwise combination of Microsoft.Win32.RegistryRights values that specifies the desired security access.</param>
        [ComVisible(false)]
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        public TransactedRegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights)
        {
            return InternalOpenSubKey(name, permissionCheck, (int)rights);
        }

        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        private TransactedRegistryKey InternalOpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, int rights)
        {
            ValidateKeyName(name);
            ValidateKeyMode(permissionCheck);
            ValidateKeyRights(rights);
            EnsureNotDisposed();
            name = FixupName(name); // Fixup multiple slashes to a single slash

            CheckOpenSubKeyPermission(name, permissionCheck);
            SafeRegistryHandle result = null;
            int ret = 0;

            SafeTransactionHandle safeTransactionHandle = GetTransactionHandle();

            ret = RegOpenKeyTransactedWrapper(_hkey, name, 0, rights, out result, safeTransactionHandle, IntPtr.Zero);

            if (ret == 0 && !result.IsInvalid)
            {
                TransactedRegistryKey key = new TransactedRegistryKey(result, (permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree), false,
                                                                      Transaction.Current, safeTransactionHandle);
                key._keyName = _keyName + "\\" + name;
                key._checkMode = permissionCheck;
                return key;
            }

            // Return null if we didn't find the key.
            if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL)
            {
                // We need to throw SecurityException here for compatibility reason,
                // although UnauthorizedAccessException will make more sense.
                throw new SecurityException(RegistryProviderStrings.Security_RegistryPermission);
            }

            return null;
        }

        // This required no security checks. This is to get around the Deleting SubKeys which only require
        // write permission. They call OpenSubKey which required read. Now instead call this function w/o security checks
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        internal TransactedRegistryKey InternalOpenSubKey(string name, bool writable)
        {
            ValidateKeyName(name);
            EnsureNotDisposed();

            int winAccess = GetRegistryKeyAccess(writable);
            SafeRegistryHandle result = null;
            int ret = 0;
            SafeTransactionHandle safeTransactionHandle = GetTransactionHandle();

            ret = RegOpenKeyTransactedWrapper(_hkey, name, 0, winAccess, out result, safeTransactionHandle, IntPtr.Zero);

            if (ret == 0 && !result.IsInvalid)
            {
                TransactedRegistryKey key = new TransactedRegistryKey(result, writable, false, Transaction.Current, safeTransactionHandle);
                key._keyName = _keyName + "\\" + name;
                return key;
            }

            return null;
        }

        /// <summary>
        /// <para>Retrieves a subkey for readonly access.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>The subkey requested or null if the operation failed.</returns>
        /// <param name="name">Name or path of the subkey to open.</param>
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        public TransactedRegistryKey OpenSubKey(string name)
        {
            return OpenSubKey(name, false);
        }

        /// <summary>
        /// <para>Retrieves the count of subkeys.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>The count of subkeys.</returns>
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        public int SubKeyCount
        {
            get
            {
                CheckKeyReadPermission();
                return InternalSubKeyCount();
            }
        }

        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        internal int InternalSubKeyCount()
        {
            EnsureNotDisposed();
            // Don't require a transaction. We don't want to throw for "Base" keys.

            int subkeys = 0;
            int junk = 0;
            int ret = Win32Native.RegQueryInfoKey(_hkey,
                                      null,
                                      null,
                                      Win32Native.NULL,
                                      ref subkeys,  // subkeys
                                      null,
                                      null,
                                      ref junk,     // values
                                      null,
                                      null,
                                      null,
                                      null);

            if (ret != 0)
                Win32Error(ret, null);
            return subkeys;
        }

        /// <summary>
        /// <para>Retrieves an array of strings containing all the subkey names.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>A string array containing all the subkey names.</returns>
        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        public string[] GetSubKeyNames()
        {
            CheckKeyReadPermission();
            return InternalGetSubKeyNames();
        }

        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        internal string[] InternalGetSubKeyNames()
        {
            EnsureNotDisposed();
            // Don't require a transaction. We don't want to throw for "Base" keys.
            int subkeys = InternalSubKeyCount();
            string[] names = new string[subkeys];  // Returns 0-length array if empty.

            if (subkeys > 0)
            {
                StringBuilder name = new StringBuilder(256);
                int namelen;

                for (int i = 0; i < subkeys; i++)
                {
                    namelen = name.Capacity; // Don't remove this. The API's doesn't work if this is not properly initialised.
                    int ret = Win32Native.RegEnumKeyEx(_hkey,
                        i,
                        name,
                        out namelen,
                        null,
                        null,
                        null,
                        null);
                    if (ret != 0)
                        Win32Error(ret, null);
                    names[i] = name.ToString();
                }
            }

            return names;
        }

        /// <summary>
        /// <para>Retrieves the count of values.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>A count of values.</returns>
        public int ValueCount
        {
            get
            {
                CheckKeyReadPermission();
                return InternalValueCount();
            }
        }

        internal int InternalValueCount()
        {
            EnsureNotDisposed();
            // Don't require a transaction. We don't want to throw for "Base" keys.
            int values = 0;
            int junk = 0;
            int ret = Win32Native.RegQueryInfoKey(_hkey,
                                      null,
                                      null,
                                      Win32Native.NULL,
                                      ref junk,     // subkeys
                                      null,
                                      null,
                                      ref values,   // values
                                      null,
                                      null,
                                      null,
                                      null);
            if (ret != 0)
                Win32Error(ret, null);
            return values;
        }

        /// <summary>
        /// <para>Retrieves an array of strings containing all the value names.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>All the value names.</returns>
        public string[] GetValueNames()
        {
            CheckKeyReadPermission();
            EnsureNotDisposed();
            // Don't require a transaction. We don't want to throw for "Base" keys.

            int values = InternalValueCount();
            string[] names = new string[values];

            if (values > 0)
            {
                StringBuilder name = new StringBuilder(256);
                int namelen;
                int currentlen;
                int ret;

                for (int i = 0; i < values; i++)
                {
                    currentlen = name.Capacity;
                    ret = Win32Native.ERROR_MORE_DATA;

                    // loop while we get error_more_data or until we have exceeded
                    // the max name length.
                    while (Win32Native.ERROR_MORE_DATA == ret)
                    {
                        namelen = currentlen;
                        ret = Win32Native.RegEnumValue(_hkey,
                            i,
                            name,
                            ref namelen,
                            Win32Native.NULL,
                            null,
                            null,
                            null);

                        if (ret != 0)
                        {
                            if (ret != Win32Native.ERROR_MORE_DATA)
                                Win32Error(ret, null);

                            // We got ERROR_MORE_DATA. Let's see if we can make the buffer
                            // bigger.
                            if (MaxValueNameLength == currentlen)
                                Win32Error(ret, null);

                            currentlen = currentlen * 2;
                            if (MaxValueNameLength < currentlen)
                                currentlen = MaxValueNameLength;

                            // Allocate a new buffer.
                            name = new StringBuilder(currentlen);
                        }
                    }

                    names[i] = name.ToString();
                }
            }

            return names;
        }

        /// <summary>
        /// <para>Retrieves the specified value. null is returned if the value
        /// doesn't exist. Utilizes Transaction.Current for its transaction.</para>
        /// <para>Note that name can be null or "", at which point the
        /// unnamed or default value of this Registry key is returned, if any.</para>
        /// </summary>
        /// <returns>The data associated with the value.</returns>
        /// <param name="name">Name of value to retrieve.</param>
        public object GetValue(string name)
        {
            CheckValueReadPermission(name);
            return InternalGetValue(name, null, false, true);
        }

        /// <summary>
        /// <para>Retrieves the specified value. null is returned if the value
        /// doesn't exist. Utilizes Transaction.Current for its transaction.</para>
        /// <para>Note that name can be null or "", at which point the
        /// unnamed or default value of this Registry key is returned, if any.</para>
        /// </summary>
        /// <returns>The data associated with the value.</returns>
        /// <param name="name">Name of value to retrieve.</param>
        /// <param name="defaultValue">Value to return if name doesn't exist.</param>
        public object GetValue(string name, object defaultValue)
        {
            CheckValueReadPermission(name);
            return InternalGetValue(name, defaultValue, false, true);
        }

        /// <summary>
        /// <para>Retrieves the specified value. null is returned if the value
        /// doesn't exist. Utilizes Transaction.Current for its transaction.</para>
        /// <para>Note that name can be null or "", at which point the
        /// unnamed or default value of this Registry key is returned, if any.</para>
        /// </summary>
        /// <returns>The data associated with the value.</returns>
        /// <param name="name">Name of value to retrieve.</param>
        /// <param name="defaultValue">Value to return if name doesn't exist.</param>
        /// <param name="options">One of the Microsoft.Win32.RegistryValueOptions values that specifies
        /// optional processing of the retrieved value.</param>
        [ComVisible(false)]
        public object GetValue(string name, object defaultValue, RegistryValueOptions options)
        {
            if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames)
            {
                string resourceTemplate = RegistryProviderStrings.Arg_EnumIllegalVal;
                string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, options.ToString());
                throw new ArgumentException(resource);
            }

            bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames);
            CheckValueReadPermission(name);
            return InternalGetValue(name, defaultValue, doNotExpand, true);
        }

        internal object InternalGetValue(string name, object defaultValue, bool doNotExpand, bool checkSecurity)
        {
            if (checkSecurity)
            {
                // Name can be null!  It's the most common use of RegQueryValueEx
                EnsureNotDisposed();
            }

            // Don't require a transaction. We don't want to throw for "Base" keys.

            object data = defaultValue;
            int type = 0;
            int datasize = 0;

            int ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize);

            if (ret != 0)
            {
                // For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data).
                // Some OS's returned ERROR_MORE_DATA even in success cases, so we
                // want to continue on through the function.
                if (ret != Win32Native.ERROR_MORE_DATA)
                    return data;
            }

            switch (type)
            {
                case Win32Native.REG_DWORD_BIG_ENDIAN:
                case Win32Native.REG_BINARY:
                    {
                        byte[] blob = new byte[datasize];
                        ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
                        data = blob;
                    }

                    break;
                case Win32Native.REG_QWORD:
                    {    // also REG_QWORD_LITTLE_ENDIAN
                        if (datasize > 8)
                        {
                            // prevent an AV in the edge case that datasize is larger than sizeof(long)
                            goto case Win32Native.REG_BINARY;
                        }

                        long blob = 0;
                        BCLDebug.Assert(datasize == 8, "datasize==8");
                        // Here, datasize must be 8 when calling this
                        ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize);

                        data = blob;
                    }

                    break;
                case Win32Native.REG_DWORD:
                    {    // also REG_DWORD_LITTLE_ENDIAN
                        if (datasize > 4)
                        {
                            // prevent an AV in the edge case that datasize is larger than sizeof(int)
                            goto case Win32Native.REG_QWORD;
                        }

                        int blob = 0;
                        BCLDebug.Assert(datasize == 4, "datasize==4");
                        // Here, datasize must be four when calling this
                        ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize);

                        data = blob;
                    }

                    break;

                case Win32Native.REG_SZ:
                    {
                        StringBuilder blob = new StringBuilder(datasize / 2);
                        ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
                        data = blob.ToString();
                    }

                    break;

                case Win32Native.REG_EXPAND_SZ:
                    {
                        StringBuilder blob = new StringBuilder(datasize / 2);
                        ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
                        if (doNotExpand)
                            data = blob.ToString();
                        else
                            data = Environment.ExpandEnvironmentVariables(blob.ToString());
                    }

                    break;
                case Win32Native.REG_MULTI_SZ:
                    {
                        IList<string> strings = new List<string>();

                        char[] blob = new char[datasize / 2];
                        ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);

                        int cur = 0;
                        int len = blob.Length;

                        while (ret == 0 && cur < len)
                        {
                            int nextNull = cur;
                            while (nextNull < len && blob[nextNull] != (char)0)
                            {
                                nextNull++;
                            }

                            if (nextNull < len)
                            {
                                BCLDebug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0");
                                if (nextNull - cur > 0)
                                {
                                    strings.Add(new string(blob, cur, nextNull - cur));
                                }
                                else
                                {
                                    // we found an empty string.  But if we're at the end of the data,
                                    // it's just the extra null terminator.
                                    if (nextNull != len - 1)
                                        strings.Add(string.Empty);
                                }
                            }
                            else
                            {
                                strings.Add(new string(blob, cur, len - cur));
                            }

                            cur = nextNull + 1;
                        }

                        data = new string[strings.Count];
                        strings.CopyTo((string[])data, 0);
                        // data = strings.GetAllItems(String.class);
                    }

                    break;
                case Win32Native.REG_NONE:
                case Win32Native.REG_LINK:
                default:
                    break;
            }

            return data;
        }

        /// <summary>
        /// <para>Retrieves the registry data type of the value associated with the specified name.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>A RegistryValueKind value representing the registry data type of the value associated with name.</returns>
        /// <param name="name">The value name whose data type is to be retrieved.</param>
        [ComVisible(false)]
        public RegistryValueKind GetValueKind(string name)
        {
            CheckValueReadPermission(name);
            EnsureNotDisposed();

            int type = 0;
            int datasize = 0;
            int ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize);
            if (ret != 0)
                Win32Error(ret, null);

            if (!Enum.IsDefined(typeof(RegistryValueKind), type))
                return RegistryValueKind.Unknown;
            else
                return (RegistryValueKind)type;
        }

        /**
         * Retrieves the current state of the dirty property.
         *
         * A key is marked as dirty if any operation has occurred that modifies the
         * contents of the key.
         *
         * @return <b>true</b> if the key has been modified.
         */
        private bool IsDirty()
        {
            return (_state & STATE_DIRTY) != 0;
        }

        private bool IsSystemKey()
        {
            return (_state & STATE_SYSTEMKEY) != 0;
        }

        private bool IsWritable()
        {
            return (_state & STATE_WRITEACCESS) != 0;
        }

        /// <summary>
        /// <para>Retrieves the name of the key.</para>
        /// </summary>
        /// <returns>The name of the key.</returns>
        public string Name
        {
            get
            {
                EnsureNotDisposed();
                return _keyName;
            }
        }

        private void SetDirty()
        {
            _state |= STATE_DIRTY;
        }

        /// <summary>
        /// <para>Sets the specified value. Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <param name="name">Name of value to store data in.</param>
        /// <param name="value">Data to store.</param>
        public void SetValue(string name, object value)
        {
            SetValue(name, value, RegistryValueKind.Unknown);
        }

        /// <summary>
        /// <para>Sets the specified value. Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <param name="name">Name of value to store data in.</param>
        /// <param name="value">Data to store.</param>
        /// <param name="valueKind">The registry data type to use when storing the data.</param>
        [ComVisible(false)]
        public unsafe void SetValue(string name, object value, RegistryValueKind valueKind)
        {
            ArgumentNullException.ThrowIfNull(value, RegistryProviderStrings.Arg_Value);

            if (name != null && name.Length > MaxValueNameLength)
            {
                throw new ArgumentException(RegistryProviderStrings.Arg_RegValueNameStrLenBug);
            }

            if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind))
                throw new ArgumentException(RegistryProviderStrings.Arg_RegBadKeyKind);

            EnsureWriteable();

            // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction.
            VerifyTransaction();

            if (ContainsRegistryValue(name))
            { // Existing key
                CheckValueWritePermission(name);
            }
            else
            { // Creating a new value
                CheckValueCreatePermission(name);
            }

            if (valueKind == RegistryValueKind.Unknown)
            {
                // this is to maintain compatibility with the old way of autodetecting the type.
                // SetValue(string, object) will come through this codepath.
                valueKind = CalculateValueKind(value);
            }

            int ret = 0;
            try
            {
                switch (valueKind)
                {
                    case RegistryValueKind.ExpandString:
                    case RegistryValueKind.String:
                        {
                            string data = value.ToString();
                            // divide by 2 to account for unicode.
                            if (MaxValueDataLength / 2 < data.Length)
                            {
                                throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug);
                            }

                            ret = Win32Native.RegSetValueEx(_hkey,
                                name,
                                0,
                                valueKind,
                                data,
                                data.Length * 2 + 2);
                            break;
                        }

                    case RegistryValueKind.MultiString:
                        {
                            // Other thread might modify the input array after we calculate the buffer length.
                            // Make a copy of the input array to be safe.
                            string[] dataStrings = (string[])(((string[])value).Clone());

                            int sizeInBytes = 0;

                            // First determine the size of the array
                            //
                            for (int i = 0; i < dataStrings.Length; i++)
                            {
                                if (dataStrings[i] == null)
                                {
                                    throw new ArgumentException(RegistryProviderStrings.Arg_RegSetStrArrNull);
                                }

                                sizeInBytes += (dataStrings[i].Length + 1) * 2;
                            }

                            sizeInBytes += 2;

                            if (MaxValueDataLength < sizeInBytes)
                            {
                                throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug);
                            }

                            byte[] basePtr = new byte[sizeInBytes];
                            fixed (byte* b = basePtr)
                            {
                                int totalBytesMoved = 0;
                                int currentBytesMoved = 0;

                                // Write out the strings...
                                //
                                for (int i = 0; i < dataStrings.Length; i++)
                                {
                                    currentBytesMoved = System.Text.Encoding.Unicode.GetBytes(dataStrings[i], 0, dataStrings[i].Length, basePtr, totalBytesMoved);
                                    totalBytesMoved += currentBytesMoved;
                                    basePtr[totalBytesMoved] = 0;
                                    basePtr[totalBytesMoved + 1] = 0;
                                    totalBytesMoved += 2;
                                }

                                ret = Win32Native.RegSetValueEx(_hkey,
                                    name,
                                    0,
                                    RegistryValueKind.MultiString,
                                    basePtr,
                                    sizeInBytes);
                            }

                            break;
                        }

                    case RegistryValueKind.Binary:
                        byte[] dataBytes = (byte[])value;
                        if (MaxValueDataLength < dataBytes.Length)
                        {
                            throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug);
                        }

                        ret = Win32Native.RegSetValueEx(_hkey,
                            name,
                            0,
                            RegistryValueKind.Binary,
                            dataBytes,
                            dataBytes.Length);
                        break;

                    case RegistryValueKind.DWord:
                        {
                            // We need to use Convert here because we could have a boxed type cannot be
                            // unboxed and cast at the same time.  I.e. ((int)(object)(short) 5) will fail.
                            int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture);

                            ret = Win32Native.RegSetValueEx(_hkey,
                                name,
                                0,
                                RegistryValueKind.DWord,
                                ref data,
                                4);
                            break;
                        }

                    case RegistryValueKind.QWord:
                        {
                            long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture);

                            ret = Win32Native.RegSetValueEx(_hkey,
                                name,
                                0,
                                RegistryValueKind.QWord,
                                ref data,
                                8);
                            break;
                        }
                }
            }
            catch (OverflowException)
            {
                throw new ArgumentException(RegistryProviderStrings.Arg_RegSetMismatchedKind);
            }
            catch (InvalidOperationException)
            {
                throw new ArgumentException(RegistryProviderStrings.Arg_RegSetMismatchedKind);
            }
            catch (FormatException)
            {
                throw new ArgumentException(RegistryProviderStrings.Arg_RegSetMismatchedKind);
            }
            catch (InvalidCastException)
            {
                throw new ArgumentException(RegistryProviderStrings.Arg_RegSetMismatchedKind);
            }

            if (ret == 0)
            {
                SetDirty();
            }
            else
                Win32Error(ret, null);
        }

        private RegistryValueKind CalculateValueKind(object value)
        {
            // This logic matches what used to be in SetValue(string name, object value) in the v1.0 and v1.1 days.
            // Even though we could add detection for an int64 in here, we want to maintain compatibility with the
            // old behavior.
            if (value is Int32)
                return RegistryValueKind.DWord;
            else if (value is Array)
            {
                if (value is byte[])
                    return RegistryValueKind.Binary;
                else if (value is string[])
                    return RegistryValueKind.MultiString;
                else
                {
                    string resourceTemplate = RegistryProviderStrings.Arg_RegSetBadArrType;
                    string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, value.GetType().Name);
                    throw new ArgumentException(resource);
                }
            }
            else
                return RegistryValueKind.String;
        }

        /**
         * Retrieves a string representation of this key.
         *
         * @return a string representing the key.
         */
        /// <summary>
        /// <para>Retrieves a string representation of this key.</para>
        /// </summary>
        /// <returns>A string representing the key.</returns>
        public override string ToString()
        {
            EnsureNotDisposed();
            return _keyName;
        }

        /// <summary>
        /// <para>Returns the access control security for the current registry key.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>A TransactedRegistrySecurity object that describes the access control
        /// permissions on the registry key represented by the current TransactedRegistryKey.</returns>
        public TransactedRegistrySecurity GetAccessControl()
        {
            return GetAccessControl(AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
        }

        /// <summary>
        /// <para>Returns the access control security for the current registry key.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <returns>A TransactedRegistrySecurity object that describes the access control
        /// permissions on the registry key represented by the current TransactedRegistryKey.</returns>
        /// <param name="includeSections">A bitwise combination of AccessControlSections values that specifies the type of security information to get.</param>
        public TransactedRegistrySecurity GetAccessControl(AccessControlSections includeSections)
        {
            EnsureNotDisposed();
            // Don't require a transaction. We don't want to throw for "Base" keys.
            return new TransactedRegistrySecurity(_hkey, _keyName, includeSections);
        }

        /// <summary>
        /// <para>Applies Windows access control security to an existing registry key.
        /// Utilizes Transaction.Current for its transaction.</para>
        /// </summary>
        /// <param name="registrySecurity">A TransactedRegistrySecurity object that specifies the access control security to apply to the current subkey.</param>
        public void SetAccessControl(TransactedRegistrySecurity registrySecurity)
        {
            EnsureWriteable();
            ArgumentNullException.ThrowIfNull(registrySecurity);
            // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction.
            VerifyTransaction();

            registrySecurity.Persist(_hkey, _keyName);
        }

        /**
         * After calling GetLastWin32Error(), it clears the last error field,
         * so you must save the HResult and pass it to this method.  This method
         * will determine the appropriate exception to throw dependent on your
         * error, and depending on the error, insert a string into the message
         * gotten from the ResourceManager.
         */
        internal void Win32Error(int errorCode, string str)
        {
            switch (errorCode)
            {
                case Win32Native.ERROR_ACCESS_DENIED:
                    if (str != null)
                    {
                        string resourceTemplate = RegistryProviderStrings.UnauthorizedAccess_RegistryKeyGeneric_Key;
                        string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, str);
                        throw new UnauthorizedAccessException(resource);
                    }
                    else
                        throw new UnauthorizedAccessException();

                case Win32Native.ERROR_INVALID_HANDLE:
                    // **
                    // * For normal RegistryKey instances we dispose the SafeRegHandle and throw IOException.
                    // * However, for HKEY_PERFORMANCE_DATA (on a local or remote machine) we avoid disposing the
                    // * SafeRegHandle and only throw the IOException.  This is to workaround reentrancy issues
                    // * in PerformanceCounter.NextValue() where the API could throw {NullReference, ObjectDisposed, ArgumentNull}Exception
                    // * on reentrant calls because of this error code path in RegistryKey
                    // *
                    // * Normally we'd make our caller synchronize access to a shared RegistryKey instead of doing something like this,
                    // * however we shipped PerformanceCounter.NextValue() un-synchronized in v2.0RTM and customers have taken a dependency on
                    // * this behavior (being able to simultaneously query multiple remote-machine counters on multiple threads, instead of
                    // * having serialized access).
                    // *
                    // * FUTURE: Consider changing PerformanceCounterLib to handle its own Win32 RegistryKey API calls instead of depending
                    // * on Microsoft.Win32.RegistryKey, so that RegistryKey can be clean of special-cases for HKEY_PERFORMANCE_DATA.
                    //
                    _hkey.SetHandleAsInvalid();
                    _hkey = null;
                    goto default;

                case Win32Native.ERROR_FILE_NOT_FOUND:
                    {
                        string resourceTemplate = RegistryProviderStrings.Arg_RegKeyNotFound;
                        string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, errorCode.ToString(System.Globalization.CultureInfo.InvariantCulture));
                        throw new IOException(resource);
                    }

                default:
                    throw new IOException(Win32Native.GetMessage(errorCode), errorCode);
            }
        }

        internal static void Win32ErrorStatic(int errorCode, string str)
        {
            switch (errorCode)
            {
                case Win32Native.ERROR_ACCESS_DENIED:
                    if (str != null)
                    {
                        string resourceTemplate = RegistryProviderStrings.UnauthorizedAccess_RegistryKeyGeneric_Key;
                        string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, str);
                        throw new UnauthorizedAccessException(resource);
                    }
                    else
                        throw new UnauthorizedAccessException();

                default:
                    throw new IOException(Win32Native.GetMessage(errorCode), errorCode);
            }
        }

        internal static string FixupName(string name)
        {
            BCLDebug.Assert(name != null, "[FixupName]name!=null");
            if (name.Contains('\\'))
                return name;

            StringBuilder sb = new StringBuilder(name);
            FixupPath(sb);
            int temp = sb.Length - 1;
            if (sb[temp] == '\\') // Remove trailing slash
                sb.Length = temp;
            return sb.ToString();
        }

        private static void FixupPath(StringBuilder path)
        {
            int length = path.Length;
            bool fixup = false;
            char markerChar = (char)0xFFFF;

            int i = 1;
            while (i < length - 1)
            {
                if (path[i] == '\\')
                {
                    i++;
                    while (i < length)
                    {
                        if (path[i] == '\\')
                        {
                            path[i] = markerChar;
                            i++;
                            fixup = true;
                        }
                        else
                            break;
                    }
                }

                i++;
            }

            if (fixup)
            {
                i = 0;
                int j = 0;
                while (i < length)
                {
                    if (path[i] == markerChar)
                    {
                        i++;
                        continue;
                    }

                    path[j] = path[i];
                    i++;
                    j++;
                }

                path.Length += j - i;
            }
        }

        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        private void CheckOpenSubKeyPermission(string subkeyName, bool subKeyWritable)
        {
            // If the parent key is not opened under default mode, we have access already.
            // If the parent key is opened under default mode, we need to check for permission.
            if (_checkMode == RegistryKeyPermissionCheck.Default)
            {
                CheckSubKeyReadPermission(subkeyName);
            }

            if (subKeyWritable && (_checkMode == RegistryKeyPermissionCheck.ReadSubTree))
            {
                CheckSubTreeReadWritePermission(subkeyName);
            }
        }

        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        private void CheckOpenSubKeyPermission(string subkeyName, RegistryKeyPermissionCheck subKeyCheck)
        {
            if (subKeyCheck == RegistryKeyPermissionCheck.Default)
            {
                if (_checkMode == RegistryKeyPermissionCheck.Default)
                {
                    CheckSubKeyReadPermission(subkeyName);
                }
            }

            CheckSubTreePermission(subkeyName, subKeyCheck);
        }

        private void CheckSubTreePermission(string subkeyName, RegistryKeyPermissionCheck subKeyCheck)
        {
            if (subKeyCheck == RegistryKeyPermissionCheck.ReadSubTree)
            {
                if (_checkMode == RegistryKeyPermissionCheck.Default)
                {
                    CheckSubTreeReadPermission(subkeyName);
                }
            }
            else if (subKeyCheck == RegistryKeyPermissionCheck.ReadWriteSubTree)
            {
                if (_checkMode != RegistryKeyPermissionCheck.ReadWriteSubTree)
                {
                    CheckSubTreeReadWritePermission(subkeyName);
                }
            }
        }

        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        // Suppressed because keyName and subkeyName won't change.
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
        private void CheckSubKeyWritePermission(string subkeyName)
        {
            BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow creating sub key under read-only key!");
            if (_checkMode == RegistryKeyPermissionCheck.Default)
            {
                // If we want to open a subkey of a read-only key as writeable, we need to do the check.
                new RegistryPermission(RegistryPermissionAccess.Write, _keyName + "\\" + subkeyName + "\\.").Demand();
            }
        }

        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        // Suppressed because keyName and subkeyName won't change.
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
        private void CheckSubKeyReadPermission(string subkeyName)
        {
            BCLDebug.Assert(_checkMode == RegistryKeyPermissionCheck.Default, "Should be called from a key opened under default mode only!");
            new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\" + subkeyName + "\\.").Demand();
        }

        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        // Suppressed because keyName and subkeyName won't change.
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
        private void CheckSubKeyCreatePermission(string subkeyName)
        {
            BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow creating sub key under read-only key!");
            if (_checkMode == RegistryKeyPermissionCheck.Default)
            {
                new RegistryPermission(RegistryPermissionAccess.Create, _keyName + "\\" + subkeyName + "\\.").Demand();
            }
        }

        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        // Suppressed because keyName and subkeyName won't change.
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
        private void CheckSubTreeReadPermission(string subkeyName)
        {
            if (_checkMode == RegistryKeyPermissionCheck.Default)
            {
                new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\" + subkeyName + "\\").Demand();
            }
        }

        // Suppressed because keyName and subkeyName won't change.
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
        private void CheckSubTreeWritePermission(string subkeyName)
        {
            BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow writing value to read-only key!");
            if (_checkMode == RegistryKeyPermissionCheck.Default)
            {
                new RegistryPermission(RegistryPermissionAccess.Write, _keyName + "\\" + subkeyName + "\\").Demand();
            }
        }

        // Suppressed because keyName and valueName won't change.
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
        private void CheckSubTreeReadWritePermission(string subkeyName)
        {
            // If we want to open a subkey of a read-only key as writeable, we need to do the check.
            new RegistryPermission(RegistryPermissionAccess.Write | RegistryPermissionAccess.Read,
                    _keyName + "\\" + subkeyName).Demand();
        }

        // Suppressed because keyName and valueName won't change.
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
        private void CheckValueWritePermission(string valueName)
        {
            BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow writing value to read-only key!");
            // skip the security check if the key is opened under write mode
            if (_checkMode == RegistryKeyPermissionCheck.Default)
            {
                new RegistryPermission(RegistryPermissionAccess.Write, _keyName + "\\" + valueName).Demand();
            }
        }

        // Suppressed because keyName and valueName won't change.
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
        private void CheckValueCreatePermission(string valueName)
        {
            BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow creating value under read-only key!");
            // skip the security check if the key is opened under write mode
            if (_checkMode == RegistryKeyPermissionCheck.Default)
            {
                new RegistryPermission(RegistryPermissionAccess.Create, _keyName + "\\" + valueName).Demand();
            }
        }

        // Suppressed because keyName and valueName won't change.
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
        private void CheckValueReadPermission(string valueName)
        {
            if (_checkMode == RegistryKeyPermissionCheck.Default)
            {
                // only need to check for default mode (dynamic check)
                new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\" + valueName).Demand();
            }
        }

        // Suppressed because keyName won't change.
        [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
        private void CheckKeyReadPermission()
        {
            if (_checkMode == RegistryKeyPermissionCheck.Default)
            {
                // only need to check for default mode (dynamic check)
                new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\.").Demand();
            }
        }

        private bool ContainsRegistryValue(string name)
        {
            int type = 0;
            int datasize = 0;
            int retval = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize);
            return retval == 0;
        }

        private void EnsureNotDisposed()
        {
            if (_hkey == null)
            {
                throw new ObjectDisposedException(_keyName,
                                  RegistryProviderStrings.ObjectDisposed_RegKeyClosed);
            }
        }

        private void EnsureWriteable()
        {
            EnsureNotDisposed();
            if (!IsWritable())
            {
                throw new UnauthorizedAccessException(RegistryProviderStrings.UnauthorizedAccess_RegistryNoWrite);
            }
        }

        private static int GetRegistryKeyAccess(bool isWritable)
        {
            int winAccess;
            if (!isWritable)
            {
                winAccess = Win32Native.KEY_READ;
            }
            else
            {
                winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE;
            }

            return winAccess;
        }

        private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode)
        {
            int winAccess = 0;
            switch (mode)
            {
                case RegistryKeyPermissionCheck.ReadSubTree:
                case RegistryKeyPermissionCheck.Default:
                    winAccess = Win32Native.KEY_READ;
                    break;

                case RegistryKeyPermissionCheck.ReadWriteSubTree:
                    winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE;
                    break;

                default:
                    BCLDebug.Assert(false, "unexpected code path");
                    break;
            }

            return winAccess;
        }

        // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
        private RegistryKeyPermissionCheck GetSubKeyPermissionCheck(bool subkeyWritable)
        {
            if (_checkMode == RegistryKeyPermissionCheck.Default)
            {
                return _checkMode;
            }

            if (subkeyWritable)
            {
                return RegistryKeyPermissionCheck.ReadWriteSubTree;
            }
            else
            {
                return RegistryKeyPermissionCheck.ReadSubTree;
            }
        }

        private static void ValidateKeyName(string name)
        {
            ArgumentNullException.ThrowIfNull(name, RegistryProviderStrings.Arg_Name);

            int nextSlash = name.IndexOf('\\');
            int current = 0;
            while (nextSlash != -1)
            {
                if ((nextSlash - current) > MaxKeyLength)
                    throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrLenBug);

                current = nextSlash + 1;
                nextSlash = name.IndexOf('\\', current);
            }

            if ((name.Length - current) > MaxKeyLength)
                throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrLenBug);
        }

        private static void ValidateKeyMode(RegistryKeyPermissionCheck mode)
        {
            if (mode < RegistryKeyPermissionCheck.Default || mode > RegistryKeyPermissionCheck.ReadWriteSubTree)
            {
                throw new ArgumentException(RegistryProviderStrings.Argument_InvalidRegistryKeyPermissionCheck);
            }
        }

        private static void ValidateKeyRights(int rights)
        {
            if (0 != (rights & ~((int)RegistryRights.FullControl)))
            {
                // We need to throw SecurityException here for compatibility reason,
                // although UnauthorizedAccessException will make more sense.
                throw new SecurityException(RegistryProviderStrings.Security_RegistryPermission);
            }
        }

        private void VerifyTransaction()
        {
            // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction.
            if (_myTransaction == null)
            {
                throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_NotAssociatedWithTransaction);
            }

            if (!_myTransaction.Equals(Transaction.Current))
            {
                throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_MustUseSameTransaction);
            }
        }
        // Win32 constants for error handling
        private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
        private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
        private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
    }
}