Esempio n. 1
1
        public static CleanupHandler InitializeHandler(string VolumeCacheName, string TargetDriveLetter)
        {
            var evcProps = new CleanupHandler()
            {
                DefaultName = VolumeCacheName
            };

            using (var rKey = Registry.LocalMachine.OpenSubKey(VolumeCacheStoreKey + VolumeCacheName, false))
            {
                // StateFlags specify if a particular handler was used last time Disk Cleanup ran as Administrator
                evcProps.StateFlag   = (int)rKey.GetValue("StateFlags", 0) == 0 ? false : true;
                evcProps.HandlerGuid = new Guid((string)rKey.GetValue(null));
                object evcInstance;
                // This is needed due to Data Driven Cleaner {C0E13E61-0CC6-11d1-BBB6-0060978B2AE6} always throwing E_NOTIMPLEMENTED on <= Windows 7
                try { evcInstance = Activator.CreateInstance(Type.GetTypeFromCLSID(evcProps.HandlerGuid)); }
                catch
                {
                    //System.Windows.Forms.MessageBox.Show(evcProps.HandlerGuid.ToString(), "Failed to load provider");
                    return(null);
                }
                // Check if newer interface with InitializeEx is available
                if (evcInstance is IEmptyVolumeCache2 ex2Instance)
                {
                    int initRes = ex2Instance.InitializeEx(rKey.Handle.DangerousGetHandle(), TargetDriveLetter, VolumeCacheName, out IntPtr ppwszDisplayName, out IntPtr ppwszDescription, out IntPtr ppwszBtnText, out uint pdwFlags);
                    // Discard handler if initialization failed
                    if (initRes != 0)
                    {
                        try { ex2Instance.Deactivate(out uint dummy); } catch { }
                        Marshal.FinalReleaseComObject(ex2Instance);
                        return(null);
                    }
                    evcProps.DisplayName = Marshal.PtrToStringAuto(ppwszDisplayName);
                    evcProps.Description = Marshal.PtrToStringAuto(ppwszDescription);
                    evcProps.ButtonText  = Marshal.PtrToStringAuto(ppwszBtnText);
                    evcProps.Flags       = (HandlerFlags)pdwFlags;
                    evcProps.Instance    = ex2Instance;
                }
                else
                {
                    // It appears that only the old interface is available
                    IEmptyVolumeCache vcInstance = (IEmptyVolumeCache)evcInstance;
                    int initRes = vcInstance.Initialize(rKey.Handle.DangerousGetHandle(), TargetDriveLetter, out IntPtr ppwszDisplayName, out IntPtr ppwszDescription, out uint pdwFlags);
                    // Discard handler if initialization failed
                    if (initRes != 0)
                    {
                        try { vcInstance.Deactivate(out uint dummy); } catch { }
                        Marshal.FinalReleaseComObject(vcInstance);
                        return(null);
                    }
                    evcProps.DisplayName = Marshal.PtrToStringAuto(ppwszDisplayName);
                    evcProps.Description = Marshal.PtrToStringAuto(ppwszDescription);
                    evcProps.Flags       = (HandlerFlags)pdwFlags;
                    evcProps.Instance    = vcInstance;
                }
                evcProps.IconHint = rKey.GetValue("IconPath", null);
                if (evcProps.IconHint == null)
                {
                    // Icons can sometimes be provided by the DefaultIcon of a handler's class
                    RegistryKey hkrKey = Registry.ClassesRoot.OpenSubKey(string.Format("CLSID\\{{{0}}}\\DefaultIcon", evcProps.HandlerGuid));
                    if (hkrKey != null)
                    {
                        evcProps.IconHint = (string)hkrKey.GetValue(null);
                        hkrKey.Close();
                    }
                }
                evcProps.PreProcHint  = (string)rKey.GetValue("PreCleanupString", null);
                evcProps.PostProcHint = (string)rKey.GetValue("CleanupString", null);
                #region Multi-Type registry value to uint loader
                object optValObj = rKey.GetValue("Flags");
                if (optValObj != null)
                {
                    RegistryValueKind optValKind = rKey.GetValueKind("Flags");
                    uint optVal = 0;
                    switch (optValKind)
                    {
                    case RegistryValueKind.Binary:
                        optVal = BitConverter.ToUInt32((byte[])optValObj, 0);
                        break;

                    case RegistryValueKind.DWord:
                        optVal = (uint)(int)optValObj;
                        break;
                    }
                    if (optVal > 0)
                    {
                        evcProps.DataDrivenFlags = (DDCFlags)optVal;
                    }
                }
                optValObj = rKey.GetValue("Priority");
                if (optValObj != null)
                {
                    RegistryValueKind optValKind = rKey.GetValueKind("Priority");
                    uint optVal = 0;
                    switch (optValKind)
                    {
                    case RegistryValueKind.Binary:
                        optVal = BitConverter.ToUInt32((byte[])optValObj, 0);
                        break;

                    case RegistryValueKind.DWord:
                        optVal = (uint)(int)optValObj;
                        break;
                    }
                    if (optVal > 0)
                    {
                        evcProps.Priority = optVal;
                    }
                }
                #endregion
                // Multiple paths strike again, we check if there's a Property Bag or PE resource contain strings in case we still have none loaded
                if (evcProps.DisplayName == null)
                {
                    string optionalValue = (string)rKey.GetValue("PropertyBag", null);
                    if (optionalValue != null)
                    {
                        IPropertyBag pbInstance = (IPropertyBag)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(optionalValue)));
                        object       bagContent = "";
                        if (pbInstance.Read("display", ref bagContent, IntPtr.Zero) == 0)
                        {
                            evcProps.DisplayName = (string)bagContent;
                        }
                        if (pbInstance.Read("Description", ref bagContent, IntPtr.Zero) == 0)
                        {
                            evcProps.Description = (string)bagContent;
                        }
                        if (pbInstance.Read("AdvancedButtonText", ref bagContent, IntPtr.Zero) == 0)
                        {
                            evcProps.ButtonText = (string)bagContent;
                        }
                        Marshal.FinalReleaseComObject(pbInstance);
                        return(evcProps);
                    }
                    optionalValue = (string)rKey.GetValue("display", null);
                    if (optionalValue != null)
                    {
                        StringBuilder strBld = new StringBuilder(513);
                        NativeMethods.SHLoadIndirectString(optionalValue, strBld, 513, IntPtr.Zero);
                        evcProps.DisplayName = strBld.ToString();
                        optionalValue        = (string)rKey.GetValue("Description", null);
                        strBld.Clear();
                        NativeMethods.SHLoadIndirectString(optionalValue, strBld, 513, IntPtr.Zero);
                        evcProps.Description = strBld.ToString();
                        optionalValue        = (string)rKey.GetValue("AdvancedButtonText", null);
                        strBld.Clear();
                        NativeMethods.SHLoadIndirectString(optionalValue, strBld, 513, IntPtr.Zero);
                        evcProps.ButtonText = strBld.ToString();
                        return(evcProps);
                    }
                }
            }
            if (evcProps.DisplayName == null)
            {
                evcProps.DisplayName = VolumeCacheName;
            }
            return(evcProps);
        }
        private static void SetPolicyRegistryKey(string path, string name, object value, RegistryValueKind kind)
        {
            const string keyPath = @"Software\Microsoft\Windows\CurrentVersion\Group Policy Objects";
            using (var rk = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default))
            {
                List<string> certKeys;
                using (var srk = rk.OpenSubKey(keyPath))
                {
                    if (srk == null)
                    {
                        throw new ApplicationException("无法打开注册表项:" + keyPath);
                    }
                    certKeys = srk.GetSubKeyNames().Where(x => x.EndsWith("Machine")).Select(x => string.Format("{0}\\{1}\\{2}", keyPath, x, path))
                        //.Where(x => rk.OpenSubKey(x) == null)
                        .ToList();
                }

                foreach (var key in certKeys)
                {
                    using (var skey = rk.CreateSubKey(key))
                    {
                        if (skey != null) skey.SetValue(name, value, kind);
                    }
                }
            }

        }
		private static int RegEnumValue (IntPtr keyBase,
		int index, StringBuilder nameBuffer,
		ref int nameLength, IntPtr reserved,
		ref RegistryValueKind type, IntPtr data, IntPtr dataLength)
		{
			throw new System.NotImplementedException();
		}
Esempio n. 4
0
        public bool set(String key, String val, RegistryValueKind type)
        {
            RegistryKey reg;
            int result = 1;
            string[] keysplit = (key).Split(System.IO.Path.DirectorySeparatorChar);
            string root = keysplit[0];
            string name = keysplit[keysplit.Length - 1];
            string path = key.Replace(root + @"\", "").Replace(@"\" + name, "");
            switch (root)
            {
                case "HKCU":
                    reg = Registry.CurrentUser;
                    break;
                case "HKLM":
                    reg = Registry.LocalMachine;
                    break;
                default:
                    return false;
            }

            reg = reg.CreateSubKey(path);
            if (reg == null) result = 0;
            reg.SetValue(name, val, type);
            object regObj = reg.GetValue(name);
            if (regObj == null) result = 0;
            reg.Close();
            reg = null;
            if (result == 0) return false; else return true;

        }
Esempio n. 5
0
 /// <summary>
 /// Constructs a key value pair with the given valueName, valueObject, and valueKind.  
 /// Sets valueKind to RegistryValueKind.Unknown which will cause any call to RegistryKey.SetValue to attempt to dynamically derive the type from the actual type of the ValueObject.
 /// </summary>
 public RegValueSpec(string valueName, object valueObject, RegistryValueKind valueKind)
     : this()
 {
     ValueName = valueName;
     ValueObject = valueObject;
     ValueKind = valueKind;
 }
Esempio n. 6
0
 public static object ConvertUIntToValueForRegistryIfNeeded(object value, RegistryValueKind kind)
 {
     if (kind == RegistryValueKind.DWord)
     {
         try
         {
             value = BitConverter.ToInt32(BitConverter.GetBytes(Convert.ToUInt32(value, CultureInfo.InvariantCulture)), 0);
         }
         catch (OverflowException)
         {
         }
         return value;
     }
     if (kind == RegistryValueKind.QWord)
     {
         try
         {
             value = BitConverter.ToInt64(BitConverter.GetBytes(Convert.ToUInt64(value, CultureInfo.InvariantCulture)), 0);
         }
         catch (OverflowException)
         {
         }
     }
     return value;
 }
Esempio n. 7
0
		static extern uint RegQueryValueEx(
			UIntPtr hKey,
			string lpValueName,
			IntPtr lpReserved,
			out RegistryValueKind lpType,
			StringBuilder lpData,
			ref int lpcbData);
        public void RegSzOddByteLength(RegistryValueKind kind, byte[] contents)
        {
            const string TestValueName = "CorruptData2";

            SafeRegistryHandle handle = TestRegistryKey.Handle;
            int ret = Interop.mincore.RegSetValueEx(handle, TestValueName, 0,
                kind, contents, contents.Length);
            Assert.Equal(0, ret);
            try
            {
                object o = TestRegistryKey.GetValue(TestValueName);

                string s;
                if (kind == RegistryValueKind.MultiString)
                {
                    Assert.IsType<string[]>(o);
                    var strings = (string[])o;
                    Assert.Equal(1, strings.Length);
                    s = strings[0];
                }
                else
                {
                    Assert.IsType<string>(o);
                    s = (string)o;
                }

                Assert.Equal(2, s.Length);
                Assert.Equal(0x506, s[0]);
                Assert.Equal(0x6, s[1]);
            }
            finally
            {
                TestRegistryKey.DeleteValue(TestValueName);
            }
        }
Esempio n. 9
0
 public static object ConvertValueToUIntFromRegistryIfNeeded(string name, object value, RegistryValueKind kind)
 {
     try
     {
         if (kind == RegistryValueKind.DWord)
         {
             value = (int) value;
             if (((int) value) < 0)
             {
                 value = BitConverter.ToUInt32(BitConverter.GetBytes((int) value), 0);
             }
             return value;
         }
         if (kind == RegistryValueKind.QWord)
         {
             value = (long) value;
             if (((long) value) < 0L)
             {
                 value = BitConverter.ToUInt64(BitConverter.GetBytes((long) value), 0);
             }
         }
     }
     catch (IOException)
     {
     }
     return value;
 }
Esempio n. 10
0
		public static void PutObjectValue(string key, string valuename, string value, bool bHKLM, RegistryValueKind kind = RegistryValueKind.Unknown)
        {
            using (RegistryKey regkey = bHKLM ? Registry.LocalMachine.CreateSubKey(key) : Registry.CurrentUser.CreateSubKey(key))
            {
                regkey.SetValue(valuename, value, kind);
            }
        }
Esempio n. 11
0
 internal static extern int RegSetValueEx(
     SafeRegistryHandle hKey,
     String lpValueName,
     int Reserved,
     RegistryValueKind dwType,
     String lpData,
     int cbData);
Esempio n. 12
0
        public static object ConvertValueToUIntFromRegistryIfNeeded(string name, object value, RegistryValueKind kind)
        {
            try
            {
                // Workaround for CLR bug that doesn't support full range of DWORD or QWORD
                if (kind == RegistryValueKind.DWord)
                {
                    value = (int)value;
                    if ((int)value < 0)
                    {
                        value = BitConverter.ToUInt32(BitConverter.GetBytes((int)value), 0);
                    }
                }
                else if (kind == RegistryValueKind.QWord)
                {
                    value = (long)value;
                    if ((long)value < 0)
                    {
                        value = BitConverter.ToUInt64(BitConverter.GetBytes((long)value), 0);
                    }
                }
            }
            catch (System.IO.IOException)
            {
                // This is expected if the value does not exist.
            }

            return value;
        }
 public RegistryValueSnapshot(string name, string value, RegistryValueKind type)
     : this()
 {
     this.Name = name;
       this.Value = value;
       this.Type = type;
 }
 public SetWindowsRegistryValueOperation(WindowsRegistryRoot root, string key, string valueName, string valueData, RegistryValueKind valueKind)
 {
     _root = root;
     _key = key;
     _valueName = valueName;
     _valueData = valueData;
     _valueKind = valueKind;
 }
Esempio n. 15
0
 internal AddinKeyValue(WatchController root, AddinKey parent, string valueName, RegistryValueKind valueKind, object value)
 {
     _root = root;
     _parent = parent;
     _valueName = valueName;
     _valueKind = valueKind;
     _value = value;
 }
Esempio n. 16
0
 public ValueForm(string name, RegistryValueKind type, object value)
     : this()
 {
     this.IsEdit = true;
     this.ValueName = name;
     this.ValueType = type;
     this.ValueValue = value;
 }
Esempio n. 17
0
 public RegChange(RegOperations regOp, RegBasekeys regBase, string subKey, bool is32BitKey)
 {
     RegOperation = regOp;
     RegBasekey = regBase;
     SubKey = subKey;
     RegValueKind = RegistryValueKind.String;
     Is32BitKey = is32BitKey;
 }
 public ConfigRegistryItem(ConfigEngine engine, string itemName, string path, string name, object value, RegistryValueKind kind)
     : base(engine, itemName)
 {
     _path = path;
     _name = name;
     _value = value;
     _kind = kind;
 }
Esempio n. 19
0
 public UtilsRegistryEntry Add(RegistryValueKind kind, object value)
 {
     RegistryKey key = _parent.Open(true);
     string[] names = key.GetValueNames();
     string name = GetNewStringValueName(names, kind.ToString());
     key.SetValue(name, value, kind);
     key.Close();
     return new UtilsRegistryEntry(_parent, name);
 }
        private uint RegSetValueExACallback(IntPtr hKey, string lpValueName, int lpReserved, RegistryValueKind dwType, IntPtr lpData, uint cbData)
        {
            bool tempBuffer = false;
            if (dwType == RegistryValueKind.String && lpData != IntPtr.Zero) tempBuffer = FilterWriteBuffer(ref lpData, ref cbData, unicode: false);

            uint result = UnsafeNativeMethods.RegSetValueExA(hKey, lpValueName, lpReserved, dwType, lpData, cbData);
            if (tempBuffer) Marshal.FreeHGlobal(lpData);
            return result;
        }
Esempio n. 21
0
		public CreateRegistryValueTask(string serverName, RegistryHive hive, string key, string valueName, RegistryValueKind valueType, object value)
		{
			ServerName = serverName;
			Hive = hive;
			Key = key;
			_valueName = valueName;
			_valueType = valueType;
			_value = value;
		}
        public void SetValueWithUnknownValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind)
        {
            string valueName = "Testing_" + testIndex.ToString();

            Registry.SetValue(_testRegistryKey.Name, valueName, testValue, RegistryValueKind.Unknown);
            Assert.Equal(testValue.ToString(), _testRegistryKey.GetValue(valueName).ToString());
            Assert.Equal(expectedValueKind, _testRegistryKey.GetValueKind(valueName));
            _testRegistryKey.DeleteValue(valueName);
        }
Esempio n. 23
0
        internal void CreateComponentValue(RegistryKey componentKey, string name, object value, RegistryValueKind kind)
        {
            if (null == componentKey)
                throw new ArgumentNullException("Unable to find specified registry key.");

            if (componentKey.GetValue(name, null) != null && componentKey.GetValueKind(name) != kind)
                componentKey.DeleteValue(name, false);

            componentKey.SetValue(name, value, kind);
        }
        public void SetValueWithExpandStringValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind)
        {
            string valueName = "Testing_" + testIndex.ToString();
            expectedValueKind = RegistryValueKind.ExpandString;

            Registry.SetValue(TestRegistryKey.Name, valueName, testValue, expectedValueKind);
            Assert.Equal(testValue.ToString(), TestRegistryKey.GetValue(valueName).ToString());
            Assert.Equal(expectedValueKind, TestRegistryKey.GetValueKind(valueName));
            TestRegistryKey.DeleteValue(valueName);
        }
Esempio n. 25
0
 public RegChange(RegOperations regOp, RegBasekeys regBase, string subKey, bool is32BitKey, string valueName, object valueData, RegistryValueKind valueType)
 {
     RegOperation = regOp;
     RegBasekey = regBase;
     SubKey = subKey;
     ValueData = valueData;
     ValueName = valueName;
     RegValueKind = valueType;
     Is32BitKey = is32BitKey;
 }
Esempio n. 26
0
        public static void SetValue(string keyName, string valueName, object value, RegistryValueKind valueKind)
        {
            string subKeyName;
            RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out subKeyName);

            using (RegistryKey key = basekey.CreateSubKey(subKeyName))
            {
                Debug.Assert(key != null, "An exception should be thrown if failed!");
                key.SetValue(valueName, value, valueKind);
            }
        }
 /// <remarks>引用组件来自:https://bitbucket.org/MartinEden/local-policy/overview </remarks>
 private static void SetPolicyKey(string path, string name, object value, RegistryValueKind kind)
 {
     var gpo = new ComputerGroupPolicyObject();
     using (var machine = gpo.GetRootRegistryKey(GroupPolicySection.Machine))
     {
         using (var cerKey = machine.CreateSubKey(path))
         {
             if (cerKey != null) cerKey.SetValue(name, value, kind);
         }
     }
     gpo.Save();
 }
 private uint RegQueryValueExACallback(IntPtr hKey, string lpValueName, IntPtr lpReserved, out RegistryValueKind dwType, IntPtr lpData, ref uint cbData)
 {
     string filteredData = GetFilteredValue(hKey, lpValueName);
     if (filteredData == null)
     { // Pass call through unmodified
         return UnsafeNativeMethods.RegQueryValueExA(hKey, lpValueName, lpReserved, out dwType, lpData, ref cbData);
     }
     else
     { // Write filtered result to buffer
         dwType = RegistryValueKind.String;
         return WriteStringToBuffer(lpData, ref cbData, false, filteredData);
     }
 }
Esempio n. 29
0
        internal void CreateComponentValue(SingletonSettings.RegisterMode mode, string key, string name, object value, RegistryValueKind kind)
        {
            RegistryKey componentKey;
            if (mode == SingletonSettings.RegisterMode.System)
                componentKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(key, true);
            else
                componentKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(_userBypass + key, true);

            if (null == componentKey)
                throw new ArgumentOutOfRangeException("Unable to find specified registry key.");

            CreateComponentValue(componentKey, name, value, kind);
        }
Esempio n. 30
0
        /// <summary>
        /// Записывает в реестр бинарные данные
        /// </summary>
        /// <param name="keyName">Имя ключа</param>
        /// <param name="path">Путь к ключу (HKCU\\software\\)</param>
        /// <param name="value">Значение</param>
        /// <param name="registryValueKind">Тип</param>
        public static void SetBinaryValue(string keyName, string path, object value, RegistryValueKind registryValueKind)
        {
            RegistryKey regKey = Registry.CurrentUser.CreateSubKey("software\\" + path);

            if (regKey == null)
            {
                DebugHelper.WriteLogEntry("Не удалось сохранить значение " + keyName + " в реестр");
            }
            else
            {
                regKey.SetValue(keyName, value, registryValueKind);
                regKey.Close();
            }
        }
Esempio n. 31
0
		protected static string GetRegistryKeyDisplayString(RegistryHive hive, string key,
			string valueName = null, RegistryValueKind valueKind = RegistryValueKind.None)
		{
			var result = new StringBuilder();
			result.AppendFormat(@"{0}\{1}", hive.AsRegistryHiveString(), key);
			if (string.IsNullOrEmpty(valueName))
				return result.ToString();

			result.AppendFormat(@"\{0}", valueName);
			if (valueKind == RegistryValueKind.None)
				return result.ToString();

			result.AppendFormat(@":{0}", valueKind.AsRegistryValueTypeString());
			return result.ToString();
		}
Esempio n. 32
0
 /// <summary>
 /// Create a new registry handler description
 /// </summary>
 /// <param name="keyName"></param>
 /// <param name="valueName"></param>
 /// <param name="valueKind"></param>
 public RegistrySettingHandlerDescription(string keyName, string valueName, RegistryValueKind valueKind) : base(HandlerKind.Registry)
 {
     KeyName   = keyName;
     ValueName = valueName;
     ValueKind = valueKind;
 }
Esempio n. 33
0
        public static void SetPolicySetting(string registryInformation, string settingValue, RegistryValueKind registryValueKind)
        {
            string             valueName;
            GroupPolicySection section;
            string             key = Key(registryInformation, out valueName, out section);

            // Thread must be STA
            Exception exception = null;
            var       t         = new Thread(() =>
            {
                try
                {
                    var gpo = new ComputerGroupPolicyObject();
                    using (RegistryKey rootRegistryKey = gpo.GetRootRegistryKey(section))
                    {
                        // Data can't be null so we can use this value to indicate key must be delete
                        if (settingValue == null)
                        {
                            using (RegistryKey subKey = rootRegistryKey.OpenSubKey(key, true))
                            {
                                if (subKey != null)
                                {
                                    subKey.DeleteValue(valueName);
                                }
                            }
                        }
                        else
                        {
                            using (RegistryKey subKey = rootRegistryKey.CreateSubKey(key))
                            {
                                subKey.SetValue(valueName, settingValue, registryValueKind);
                            }
                        }
                    }

                    gpo.Save();
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
            });

            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            t.Join();

            if (exception != null)
            {
                throw exception;
            }
        }
Esempio n. 34
0
        private static int SetValue(UIntPtr rootKey, string Path, string Name, object Value, RegistryValueKind RegType, Platform hive)
        {
            GCHandle gch = new GCHandle();
            IntPtr   ptr;
            int      Size;

            //  So we have to figure out the type
            if ((RegType == RegistryValueKind.Unknown))
            {
                switch (Value.GetType().ToString())
                {
                case "System.String":
                    RegType = RegistryValueKind.String;
                    break;

                case "System.Int32":
                    RegType = RegistryValueKind.DWord;
                    break;

                case "System.Int64":
                    RegType = RegistryValueKind.QWord;
                    break;

                case "System.String[]":
                    RegType = RegistryValueKind.MultiString;
                    break;

                case "System.Byte[]":
                    RegType = RegistryValueKind.Binary;
                    break;

                default:
                    RegType = RegistryValueKind.String;
                    Value   = Value.ToString();
                    break;
                }
            }
            switch (RegType)
            {
            case RegistryValueKind.Binary:
            {
                byte[] temp = (byte[])
                              Value;

                Size = temp.Length;
                gch  = GCHandle.Alloc(temp, GCHandleType.Pinned);
                ptr  = Marshal.UnsafeAddrOfPinnedArrayElement(temp, 0);
            }
            break;

            case RegistryValueKind.DWord:
            {
                int temp = (int)Value;
                Size = 4;
                ptr  = Marshal.AllocHGlobal(Size);
                Marshal.WriteInt32(ptr, 0, temp);
            }
            break;

            case RegistryValueKind.ExpandString:
            {
                string temp = Value.ToString();
                Size = ((temp.Length + 1) * Marshal.SystemDefaultCharSize);
                ptr  = Marshal.StringToHGlobalAuto(temp);
            }
            break;

            case RegistryValueKind.MultiString:
            {
                string[] lines = (string[])Value;
                //  Calculate the total size, including the terminating null
                Size = 0;
                foreach (string s in lines)
                {
                    Size += (s.Length + 1) * Marshal.SystemDefaultCharSize;
                }
                Size += Marshal.SystemDefaultCharSize;
                ptr   = Marshal.AllocHGlobal(Size);
                int index = 0;
                foreach (string s in lines)
                {
                    IntPtr tempPtr;
                    char[] tempArray = s.ToCharArray();
                    tempPtr = new IntPtr(ptr.ToInt64() + index);
                    Marshal.Copy(tempArray, 0, tempPtr, tempArray.Length);
                    index += (tempArray.Length + 1) * Marshal.SystemDefaultCharSize;
                }
            }
            break;

            case RegistryValueKind.QWord:
            {
                long temp = (long)Value;
                Size = 8;
                ptr  = Marshal.AllocHGlobal(Size);
                Marshal.WriteInt64(ptr, 0, temp);
            }
            break;

            case RegistryValueKind.String:
            {
                string temp = Value.ToString();
                Size = ((temp.Length + 1) * Marshal.SystemDefaultCharSize);
                ptr  = Marshal.StringToHGlobalAuto(temp);
            }
            break;

            default:
                throw new ApplicationException("Registry type of " + RegType + " is not supported");
            }
            //  let's do it!


            UIntPtr hKey = UIntPtr.Zero;
            uint    sam  = KEY_SET_VALUE;

            if ((GetPlatform() == Platform.X64))
            {
                if (Platform.X64 == hive)
                {
                    sam |= KEY_WOW64_64KEY;
                }
                else if (Platform.X86 == hive)
                {
                    sam |= KEY_WOW64_32KEY;
                }
            }
            int HRES = 0;

            HRES = RegOpenKeyEx(rootKey, Path, 0, sam, out hKey);
            if (HRES == 0)
            {
                HRES = RegSetValueEx(hKey, Name, 0, RegType, ptr, Size);
                if ((HRES != 0))
                {
                    throw new Win32Exception(HRES);
                }
                //  clean up
                if (gch.IsAllocated)
                {
                    gch.Free();
                }
                else
                {
                    Marshal.FreeHGlobal(ptr);
                }
                RegCloseKey(hKey);
            }
            return(HRES);
        }
Esempio n. 35
0
 public static extern bool SetupDiGetCustomDeviceProperty(SafeDeviceInfoSetHandle DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, string CustomPropertyName, DICUSTOMDEVPROP Flags, out RegistryValueKind PropertyRegDataType, Byte[] PropertyBuffer, int PropertyBufferSize, out int RequiredSize);
Esempio n. 36
0
 private void SetValueCore(string name, Object value, RegistryValueKind valueKind)
 {
     // TODO: Implement this
     throw new PlatformNotSupportedException();
 }
Esempio n. 37
0
 // This dummy method is added to have the same implemenatation of Registry class.
 // Its not being used anywhere.
 public void SetValue(string name, object value, RegistryValueKind valueKind)
 {
 }
Esempio n. 38
0
 public static bool TryWriteRegistryKey(string path, string name, object value, RegistryValueKind kind)
 {
     try
     {
         // Use current user, no need for admin permissions
         RegistryKey key = Registry.CurrentUser.OpenSubKey(path, true);
         if (key == null)
         {
             key = CreateRegistryPath(Registry.CurrentUser, path);
         }
         key.SetValue(name, value, kind);
         return(true);
     }
     catch {
         return(false);
     }
 }
Esempio n. 39
0
 private static int MapRegistryValueKind(RegistryValueKind registryValueKind)
 {
     return((int)registryValueKind);
 }
Esempio n. 40
0
        public void SetValue(string name, object value, RegistryValueKind valueKind)
        {
            this.SetDirty();
            if (name == null)
            {
                name = string.Empty;
            }
            switch (valueKind)
            {
            case RegistryValueKind.String:
                if (value is string)
                {
                    this.values[name] = value;
                    return;
                }
                goto IL_186;

            case RegistryValueKind.ExpandString:
                if (value is string)
                {
                    this.values[name] = new ExpandString((string)value);
                    return;
                }
                goto IL_186;

            case RegistryValueKind.Binary:
                if (value is byte[])
                {
                    this.values[name] = value;
                    return;
                }
                goto IL_186;

            case RegistryValueKind.DWord:
                if (value is long && (long)value < 2147483647L && (long)value > -2147483648L)
                {
                    this.values[name] = (int)((long)value);
                    return;
                }
                if (value is int)
                {
                    this.values[name] = value;
                    return;
                }
                goto IL_186;

            case RegistryValueKind.MultiString:
                if (value is string[])
                {
                    this.values[name] = value;
                    return;
                }
                goto IL_186;

            case RegistryValueKind.QWord:
                if (value is int)
                {
                    this.values[name] = (long)((int)value);
                    return;
                }
                if (value is long)
                {
                    this.values[name] = value;
                    return;
                }
                goto IL_186;
            }
            throw new ArgumentException("unknown value", "valueKind");
IL_186:
            throw new ArgumentException("Value could not be converted to specified type", "valueKind");
        }
        // Метод-инициализатор экземпляра класса
        private void CreateRegistryEntry(string Path, string Name, string Value, RegistryValueTypes Type, bool DeletePath, bool DeleteName)
        {
            // Переменные
            char[] pathSplitters   = new char[] { '\\' };
            char[] valuesSplitters = new char[] { '\"', '[', ']' };

            // Контроль пути
            string[] values = Path.Split(valuesSplitters, StringSplitOptions.RemoveEmptyEntries);
            if (values.Length != 1)                     // Означает наличие недопустимых символов или пустую строку
            {
                return;
            }

            pathMustBeDeleted = (values[0].Substring(0, 1) == "-");                             // Раздел помечен на удаление

            string s = values[0];

            if (pathMustBeDeleted)
            {
                s = values[0].Substring(1);
            }

            pathMustBeDeleted |= DeletePath;

            values = s.Split(pathSplitters, StringSplitOptions.RemoveEmptyEntries); // Убираем лишние слэшы
            if (values.Length < 1)                                                  // Такого не должно случиться, но вдруг там только слэшы и были
            {
                return;
            }

            if (values[0] == Registry.ClassesRoot.Name)
            {
                valueMasterKey = Registry.ClassesRoot;
            }

            /*else if (values[0] == Registry.CurrentConfig.Name)
             *      valueMasterKey = Registry.CurrentConfig;
             * else if (values[0] == Registry.CurrentUser.Name)
             *      valueMasterKey = Registry.CurrentUser;
             * else if (values[0] == Registry.LocalMachine.Name)
             *      valueMasterKey = Registry.LocalMachine;
             * else if (values[0] == Registry.Users.Name)
             *      valueMasterKey = Registry.Users;*/// Остальные разделы запрещены областью применения программы
            else
            {
                return;                         // Если корневой раздел не является допустимым
            }
            // Пересобираем путь
            valuePath = values[0];
            for (int i = 1; i < values.Length; i++)
            {
                valuePath += (pathSplitters[0].ToString() + values[i]);
            }

            // Если путь помечен на удаление, остальные параметры можно (и нужно) проигнорировать
            if (pathMustBeDeleted)
            {
                isValid = true;
                return;
            }

            // Контроль имени
            values = Name.Split(valuesSplitters, StringSplitOptions.RemoveEmptyEntries);
            if (values.Length == 0)                     // Пустая строка здесь допустима - для значения по умолчанию
            {
                valueName = "";
            }
            else if (values.Length > 1)
            {
                return;                                                 // Означает наличие недопустимых символов или пустую строку
            }
            else
            {
                valueName = values[0];
            }

            if (valueName.Contains(pathSplitters[0].ToString()))
            {
                return;
            }

            if (valueName == "@")
            {
                valueName = "";
            }

            // Контроль значения (может содержать любые символы; предполагается, что кавычки уже удалены)
            if ((Value == "-") || DeleteName)                           // Параметр помечен на удаление
            {
                nameMustBeDeleted = isValid = true;
                valueObject       = "-";
                return;
            }

            // Проверка на наличие спецификации типа
            if (Value.StartsWith("hex:"))
            {
                valueType = RegistryValueTypes.REG_BINARY;
            }
            if (Value.StartsWith("dword:"))
            {
                valueType = RegistryValueTypes.REG_DWORD;
            }
            if (Value.StartsWith("hex(2):"))
            {
                valueType = RegistryValueTypes.REG_EXPAND_SZ;
            }
            if (Value.StartsWith("hex(7):"))
            {
                valueType = RegistryValueTypes.REG_MULTI_SZ;
            }
            if (Value.StartsWith("hex(0):"))
            {
                valueType = RegistryValueTypes.REG_NONE;
            }
            if (Value.StartsWith("hex(b):"))
            {
                valueType = RegistryValueTypes.REG_QWORD;
            }

            // Обработка значения в зависимости от типа данных
            switch (valueType)
            {
            case RegistryValueTypes.REG_SZ:
                valueObject = Value;
                break;

            case RegistryValueTypes.REG_DWORD:
                try
                {
                    valueObject = (Int32.Parse(Value.Substring(6), NumberStyles.HexNumber)).ToString();
                }
                catch
                {
                    return;
                }
                break;

            case RegistryValueTypes.REG_QWORD:
                try
                {
                    Int64 a = Int64.Parse(Value.Substring(7).Replace(",", ""), NumberStyles.HexNumber);
                    a = (ExcludeByte(a, 0) << 56) | (ExcludeByte(a, 1) << 48) |
                        (ExcludeByte(a, 2) << 40) | (ExcludeByte(a, 3) << 32) |
                        (ExcludeByte(a, 4) << 24) | (ExcludeByte(a, 5) << 16) |
                        (ExcludeByte(a, 6) << 8) | ExcludeByte(a, 7);
                    valueObject = a.ToString();
                }
                catch
                {
                    return;
                }
                break;

            default:
                return;                                 // Остальные типы мы пока обрабатывать не умеем
            }

            // Переопределение, если указано (делается позже остального, чтобы не вынуждать значения,
            // пропущенные через базу, обрабатываться снова)
            if (Type != RegistryValueTypes.REG_SZ)
            {
                // Установка типа
                valueType = Type;

                switch (valueType)
                {
                case RegistryValueTypes.REG_BINARY:
                    valueTypeAsKind = RegistryValueKind.Binary;
                    break;

                case RegistryValueTypes.REG_DWORD:
                    valueTypeAsKind = RegistryValueKind.DWord;
                    break;

                case RegistryValueTypes.REG_EXPAND_SZ:
                    valueTypeAsKind = RegistryValueKind.ExpandString;
                    break;

                case RegistryValueTypes.REG_MULTI_SZ:
                    valueTypeAsKind = RegistryValueKind.MultiString;
                    break;

                case RegistryValueTypes.REG_NONE:
                    valueTypeAsKind = RegistryValueKind.None;
                    break;

                case RegistryValueTypes.REG_QWORD:
                    valueTypeAsKind = RegistryValueKind.QWord;
                    break;
                }

                // Постконтроль значения (запрет на подстановку не-чисел в числовые типы)
                try
                {
                    if (valueType == RegistryValueTypes.REG_QWORD)
                    {
                        Int64 a = Int64.Parse(valueObject);
                    }
                    if (valueType == RegistryValueTypes.REG_DWORD)
                    {
                        Int32 b = Int32.Parse(valueObject);
                    }
                }
                catch
                {
                    return;
                }
            }

            // Завершено
            isValid = true;
        }
Esempio n. 42
0
        /// <summary>
        /// Writes specified value to the registry.
        /// </summary>
        /// <param name="path">Full registry key (minus root) that will contain the value.</param>
        /// <param name="valueName">Name of the value within key that will be written.</param>
        /// <param name="value">Value to be written</param>
        public void Write(string path, string valueName, object value)
        {
            RegistryKey key     = Registry.ClassesRoot;
            RegistryKey lastKey = key;

            string[] parts = path.Split('\\');

            if (parts == null || parts.Length == 0)
            {
                return;
            }

            for (int x = 0; x < parts.Length; x++)
            {
                key = key.OpenSubKey(parts[x], true);

                if (key == null)
                {
                    key = lastKey.CreateSubKey(parts[x]);
                }

                if (x == parts.Length - 1)
                {
                    if (value is string)
                    {
                        key.SetValue(valueName, value.ToString());
                    }
                    else if (value is uint || value.GetType().IsEnum)
                    {
                        object o = key.GetValue(valueName, null);

                        if (o == null)
                        {
                            key.SetValue(valueName, value, RegistryValueKind.DWord);
                        }
                        else
                        {
                            RegistryValueKind kind = key.GetValueKind(valueName);

                            if (kind == RegistryValueKind.DWord)
                            {
                                key.SetValue(valueName, value, RegistryValueKind.DWord);
                            }
                            else if (kind == RegistryValueKind.Binary)
                            {
                                uint num = (uint)value;

                                byte[] b = new byte[4];
                                b[0] = (byte)((num & 0x000000FF) >> 0);
                                b[1] = (byte)((num & 0x0000FF00) >> 1);
                                b[2] = (byte)((num & 0x00FF0000) >> 2);
                                b[3] = (byte)((num & 0xFF000000) >> 3);


                                b[0] = (byte)((num & 0x000000FF) >> 0);
                                b[1] = (byte)((num & 0x0000FF00) >> 8);
                                b[2] = (byte)((num & 0x00FF0000) >> 16);
                                b[3] = (byte)((num & 0xFF000000) >> 24);

                                key.SetValue(valueName, b, RegistryValueKind.Binary);
                            }
                            else if (kind == RegistryValueKind.String)
                            {
                                key.SetValue(valueName, "x" + ((uint)value).ToString("X8"));
                            }
                        }
                    }
                    else if (value is Guid)
                    {
                        key.SetValue(valueName, ((Guid)value).ToString("B"));
                    }
                }

                lastKey = key;
            }

            if (key != null)
            {
                key.Close();
            }
        }
Esempio n. 43
0
 private static extern int RegQueryValueEx(IntPtr keyBase,
                                           string valueName, IntPtr reserved, ref RegistryValueKind type,
                                           ref long data, ref int dataSize);
Esempio n. 44
0
 private static extern int RegSetValueEx(IntPtr keyBase,
                                         string valueName, IntPtr reserved, RegistryValueKind type,
                                         ref long data, int rawDataLength);
 /// <summary>
 /// 设置注册表值(HKEY_CLASSES_ROOT)
 /// </summary>
 /// <param name="regeditKey">注册表项</param>
 /// <param name="regeditName">注册表键</param>
 /// <param name="regeditValue">数据</param>
 /// <param name="valueKind">RegistryValueKind 枚举</param>
 /// <returns></returns>
 public static bool SetValueClassesRoot(string regeditKey, string regeditName, object regeditValue, RegistryValueKind valueKind = RegistryValueKind.None)
 {
     return(SetValue(RegeditTypeEnum.HKEY_CLASSES_ROOT, regeditKey, regeditName, regeditValue, valueKind));
 }
Esempio n. 46
0
        /// <summary>
        /// Méthode qui permet d'écrire une valeur qui aura pour contenu une chaîne de caractères
        /// </summary>
        /// <param name="path">Chemin pour écrire la valeur à ajouter</param>
        /// <param name="valueName">Nom de la valeur à ajouter</param>
        /// <param name="value">Contenu de la valeur à ajouter</param>
        /// <param name="valueKind">Type de la valeur à ajouter</param>
        /// <param name="rV">Type de registre (32 ou 64 bits)</param>
        public static void EcrireRegistre(string path, string valueName, string value, RegistryValueKind valueKind, RegistryView rV)
        {
            var baseReg = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, rV); //Ouvre un nouveau RegistryKey qui représente la clé demandée sur l'ordinateur local avec la vue spécifiée.
            var reg     = baseReg.CreateSubKey(path);                             //Création d'une variable avec le chemin spécifié

            try
            {
                reg = baseReg.OpenSubKey(path, true); //On tente d'ouvrir la sous-clé avec le chemin indiqué

                if (reg == null)
                {
                    baseReg.CreateSubKey(path); //Si il est impossible d'ouvrir cette sous-clé, on la crée
                }

                reg.SetValue(valueName, value, valueKind); //Ensuite on défini la valeur, le nom et le type de la valeur pour cette sous-clé
            }
            catch (Exception er)
            {
                MessageBox.Show(er.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Stop); //En cas d'erreur, on affiche un message
            }
            finally
            {
                baseReg.Close();
            }
        }
Esempio n. 47
0
        public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind)
        {
            if (value == null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
            }

            if (name != null && name.Length > MaxValueLength)
            {
                throw new ArgumentException(SR.Arg_RegValStrLenBug);
            }

            if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind))
            {
                throw new ArgumentException(SR.Arg_RegBadKeyKind, nameof(valueKind));
            }

            EnsureWriteable();

            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();
                    ret = Win32Native.RegSetValueEx(hkey,
                                                    name,
                                                    0,
                                                    valueKind,
                                                    data,
                                                    checked (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)
                        {
                            ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetStrArrNull);
                        }
                        sizeInBytes = checked (sizeInBytes + (dataStrings[i].Length + 1) * 2);
                    }
                    sizeInBytes = checked (sizeInBytes + 2);

                    byte[] basePtr = new byte[sizeInBytes];
                    fixed(byte *b = basePtr)
                    {
                        IntPtr currentPtr = new IntPtr((void *)b);

                        // Write out the strings...
                        //
                        for (int i = 0; i < dataStrings.Length; i++)
                        {
                            // Assumes that the Strings are always null terminated.
                            String.InternalCopy(dataStrings[i], currentPtr, (checked (dataStrings[i].Length * 2)));
                            currentPtr = new IntPtr((long)currentPtr + (checked (dataStrings[i].Length * 2)));
                            *(char *)(currentPtr.ToPointer()) = '\0';
                            currentPtr = new IntPtr((long)currentPtr + 2);
                        }

                        *(char *)(currentPtr.ToPointer()) = '\0';
                        currentPtr = new IntPtr((long)currentPtr + 2);

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

                case RegistryValueKind.None:
                case RegistryValueKind.Binary:
                    byte[] dataBytes = (byte[])value;
                    ret = Win32Native.RegSetValueEx(hkey,
                                                    name,
                                                    0,
                                                    (valueKind == RegistryValueKind.None ? Win32Native.REG_NONE : 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)
            {
                ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
            }
            catch (InvalidOperationException)
            {
                ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
            }
            catch (FormatException)
            {
                ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
            }
            catch (InvalidCastException)
            {
                ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
            }

            if (ret == 0)
            {
                SetDirty();
            }
            else
            {
                Win32Error(ret, null);
            }
        }
Esempio n. 48
0
        //  レジストリキーをコピー
        private void CopyRegistryKey(string source, string destination)
        {
            Action <RegistryKey, RegistryKey> copyRegKey = null;

            copyRegKey = (srcKey, dstKey) =>
            {
                foreach (string paramName in srcKey.GetValueNames())
                {
                    RegistryValueKind valueKind = srcKey.GetValueKind(paramName);
                    dstKey.SetValue(
                        paramName,
                        valueKind == RegistryValueKind.ExpandString ?
                        srcKey.GetValue(paramName, "", RegistryValueOptions.DoNotExpandEnvironmentNames) :
                        srcKey.GetValue(paramName),
                        valueKind);
                }
                foreach (string keyName in srcKey.GetSubKeyNames())
                {
                    using (RegistryKey subSrcKey = srcKey.OpenSubKey(keyName, false))
                        using (RegistryKey subDstKey = dstKey.CreateSubKey(keyName, true))
                        {
                            try
                            {
                                copyRegKey(subSrcKey, subDstKey);
                            }
                            catch (System.Security.SecurityException)
                            {
                                Console.WriteLine("アクセス拒否:SecurityException\r\n" + keyName);
                            }
                            catch (UnauthorizedAccessException)
                            {
                                Console.WriteLine("アクセス拒否:UnauthorizedAccessException\r\n" + keyName);
                            }
                            catch (ArgumentException)
                            {
                                //  無効なValueKindのレジストリ値への対策
                                //  reg copyコマンドでコピー実行
                                using (Process proc = new Process())
                                {
                                    proc.StartInfo.FileName    = "reg.exe";
                                    proc.StartInfo.Arguments   = $@"copy ""{subSrcKey.ToString()}"" ""{subDstKey.ToString()}"" /s /f";
                                    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                                    proc.Start();
                                    proc.WaitForExit();
                                }
                            }
                        }
                }
            };

            //  テスト自動生成
            TestGenerator.RegistryKey(source);
            TestGenerator.RegistryKey(destination);

            using (RegistryKey sourceKey = RegistryControl.GetRegistryKey(source, false, true))
                using (RegistryKey destinationKey = RegistryControl.GetRegistryKey(destination, true, true))
                {
                    copyRegKey(sourceKey, destinationKey);
                    //  コピー元を削除する場合
                    sourceKey.DeleteSubKeyTree("");
                }
        }
Esempio n. 49
0
        /// <summary>
        /// Retrieves the part of the sqlUserInstance.dll from the registry
        /// </summary>
        /// <param name="errorState">In case the dll path is not found, the error is set here.</param>
        /// <returns></returns>
        private string GetUserInstanceDllPath(out LocalDBErrorState errorState)
        {
            string dllPath = null;

            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(LocalDBInstalledVersionRegistryKey))
            {
                if (key == null)
                {
                    errorState = LocalDBErrorState.NO_INSTALLATION;
                    return(null);
                }

                Version zeroVersion = new Version();

                Version latestVersion = zeroVersion;

                foreach (string subKey in key.GetSubKeyNames())
                {
                    Version currentKeyVersion;

                    if (!Version.TryParse(subKey, out currentKeyVersion))
                    {
                        errorState = LocalDBErrorState.INVALID_CONFIG;
                        return(null);
                    }

                    if (latestVersion.CompareTo(currentKeyVersion) < 0)
                    {
                        latestVersion = currentKeyVersion;
                    }
                }

                // If no valid versions are found, then error out
                if (latestVersion.Equals(zeroVersion))
                {
                    errorState = LocalDBErrorState.INVALID_CONFIG;
                    return(null);
                }

                // Use the latest version to get the DLL path
                using (RegistryKey latestVersionKey = key.OpenSubKey(latestVersion.ToString()))
                {
                    object instanceAPIPathRegistryObject = latestVersionKey.GetValue(InstanceAPIPathValueName);

                    if (instanceAPIPathRegistryObject == null)
                    {
                        errorState = LocalDBErrorState.NO_SQLUSERINSTANCEDLL_PATH;
                        return(null);
                    }

                    RegistryValueKind valueKind = latestVersionKey.GetValueKind(InstanceAPIPathValueName);

                    if (valueKind != RegistryValueKind.String)
                    {
                        errorState = LocalDBErrorState.INVALID_SQLUSERINSTANCEDLL_PATH;
                        return(null);
                    }

                    dllPath = (string)instanceAPIPathRegistryObject;

                    errorState = LocalDBErrorState.NONE;
                    return(dllPath);
                }
            }
        }
Esempio n. 50
0
 private void SetValue(string keyId, string valueName, int valueValue, RegistryValueKind kind)
 {
     Registry.SetValue(keyId, valueName, valueValue, kind);
     Console.WriteLine($"Setting {valueName} to {valueValue}");
 }
Esempio n. 51
0
        private string ProceedExportResult(object reg)
        {
            StringBuilder result = new StringBuilder();

            bool   useSystem = Settings.Mode == SingletonSettings.RegisterMode.System;
            string rootKey   = useSystem ? "[HKEY_LOCAL_MACHINE\\" : "[HKEY_CURRENT_USER\\";

            bool        firstFlag = true;
            IEnumerable list      = reg as IEnumerable;

            if (null != list)
            {
                foreach (object item in list)
                {
                    Type itemType = item.GetType();

                    if (firstFlag)
                    {
                        firstFlag = false;
                    }
                    else
                    {
                        result.AppendLine(String.Empty);
                    }

                    string key = itemType.InvokeMember("Key",
                                                       BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance,
                                                       null, item, new object[0]) as string;
                    if (null != key)
                    {
                        if (key.StartsWith("\\"))
                        {
                            key = key.Substring("\\".Length);
                        }
                        result.AppendLine(String.Format("{0}{1}]", rootKey, key));
                    }

                    IEnumerable values = itemType.InvokeMember("Value",
                                                               BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance,
                                                               null, item, new object[0]) as IEnumerable;

                    if (values != null)
                    {
                        foreach (object value in values)
                        {
                            Type              valueType = value.GetType();
                            string            name      = valueType.InvokeMember("Name", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, value, new object[0]) as string;
                            object            val       = valueType.InvokeMember("Value", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, value, new object[0]);
                            RegistryValueKind kind      = (RegistryValueKind)valueType.InvokeMember("Kind", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, value, new object[0]);
                            if (String.IsNullOrWhiteSpace(name))
                            {
                                name = "@";
                            }
                            else
                            {
                                name = "\"" + name + "\"";
                            }

                            switch (kind)
                            {
                            case RegistryValueKind.String:
                                result.AppendLine(String.Format("{0}=\"{1}\"", name, null != val ? val.ToString() : String.Empty));
                                break;

                            case RegistryValueKind.ExpandString:
                                result.AppendLine(String.Format("{0}={1}", name, null != val ? RegValueConverter.EncryptExpandString(val.ToString(), 13) : String.Empty));
                                break;

                            case RegistryValueKind.MultiString:
                                if (val is string[])
                                {
                                    result.AppendLine(String.Format("{0}={1}", name, null != val ? RegValueConverter.EncryptMultiString(val as string[]) : String.Empty));
                                }
                                break;

                            case RegistryValueKind.Binary:
                                if (val is byte[])
                                {
                                    result.AppendLine(String.Format("{0}={1}", name, null != val ? RegValueConverter.EncryptBinary(val as byte[]) : String.Empty));
                                }
                                break;

                            case RegistryValueKind.DWord:
                                result.AppendLine(String.Format("{0}=dword:{1}", name, RegValueConverter.ToDwordString(val)));
                                break;

                            case RegistryValueKind.QWord:
                                result.AppendLine(String.Format("{0}={1}", name, RegValueConverter.EncryptQ(Convert.ToInt64(val))));
                                break;

                            case RegistryValueKind.Unknown:
                            case RegistryValueKind.None:
                            default:
                                break;
                            }
                        }
                    }
                }
            }

            if (result.Length == 0)
            {
                return(null);
            }
            else
            {
                return(Environment.NewLine + "; --- Custom Export ---" + Environment.NewLine + result.ToString());
            }
        }
Esempio n. 52
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="name"></param>
 /// <param name="value"></param>
 /// <param name="valueType"></param>
 public RegistryNameValuePair(string name, object value, RegistryValueKind valueType)
     : this(name, value)
 {
     _valueType = valueType;
 }
Esempio n. 53
0
 public static extern bool SetupDiGetDeviceRegistryProperty(SafeDeviceInfoSetHandle DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, SPDRP Property, out RegistryValueKind PropertyRegDataType, byte[] PropertyBuffer, int PropertyBufferSize, out int RequiredSize);
Esempio n. 54
0
        private unsafe void SetValueCore(string name, object value, RegistryValueKind valueKind)
        {
            int ret = 0;

            try
            {
                switch (valueKind)
                {
                case RegistryValueKind.ExpandString:
                case RegistryValueKind.String:
                {
                    string data = value.ToString();
                    ret = Interop.Advapi32.RegSetValueEx(_hkey,
                                                         name,
                                                         0,
                                                         valueKind,
                                                         data,
                                                         checked (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());

                    // First determine the size of the array
                    //
                    // Format is null terminator between strings and final null terminator at the end.
                    //    e.g. str1\0str2\0str3\0\0
                    //
                    int sizeInChars = 1;         // no matter what, we have the final null terminator.
                    for (int i = 0; i < dataStrings.Length; i++)
                    {
                        if (dataStrings[i] == null)
                        {
                            ThrowHelper.ThrowArgumentException(SR.Arg_RegSetStrArrNull);
                        }
                        sizeInChars = checked (sizeInChars + (dataStrings[i].Length + 1));
                    }
                    int sizeInBytes = checked (sizeInChars * sizeof(char));

                    // Write out the strings...
                    //
                    char[] dataChars        = new char[sizeInChars];
                    int    destinationIndex = 0;
                    for (int i = 0; i < dataStrings.Length; i++)
                    {
                        int length = dataStrings[i].Length;
                        dataStrings[i].CopyTo(0, dataChars, destinationIndex, length);
                        destinationIndex += (length + 1);         // +1 for null terminator, which is already zero-initialized in new array.
                    }

                    ret = Interop.Advapi32.RegSetValueEx(_hkey,
                                                         name,
                                                         0,
                                                         RegistryValueKind.MultiString,
                                                         dataChars,
                                                         sizeInBytes);

                    break;
                }

                case RegistryValueKind.None:
                case RegistryValueKind.Binary:
                    byte[] dataBytes = (byte[])value;
                    ret = Interop.Advapi32.RegSetValueEx(_hkey,
                                                         name,
                                                         0,
                                                         (valueKind == RegistryValueKind.None ? Interop.Advapi32.RegistryValues.REG_NONE : 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 = Interop.Advapi32.RegSetValueEx(_hkey,
                                                         name,
                                                         0,
                                                         RegistryValueKind.DWord,
                                                         ref data,
                                                         4);
                    break;
                }

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

                    ret = Interop.Advapi32.RegSetValueEx(_hkey,
                                                         name,
                                                         0,
                                                         RegistryValueKind.QWord,
                                                         ref data,
                                                         8);
                    break;
                }
                }
            }
            catch (Exception exc) when(exc is OverflowException || exc is InvalidOperationException || exc is FormatException || exc is InvalidCastException)
            {
                ThrowHelper.ThrowArgumentException(SR.Arg_RegSetMismatchedKind);
            }

            if (ret == 0)
            {
                SetDirty();
            }
            else
            {
                Win32Error(ret, null);
            }
        }
 /// <summary>
 /// 设置注册表值(HKEY_CURRENT_USER)
 /// </summary>
 /// <param name="regeditKey">注册表项</param>
 /// <param name="regeditName">注册表键</param>
 /// <param name="regeditValue">数据</param>
 /// <param name="valueKind">RegistryValueKind 枚举</param>
 /// <returns></returns>
 public static bool SetValueCurrentUser(string regeditKey, string regeditName, object regeditValue, RegistryValueKind valueKind = RegistryValueKind.None)
 {
     return(SetValue(RegeditTypeEnum.HKEY_CURRENT_USER, regeditKey, regeditName, regeditValue, valueKind));
 }
Esempio n. 56
0
 private bool CompareValueKinds(AddinKey item, RegistryValueKind kindToCompare)
 {
     return(true);
 }
Esempio n. 57
0
 public static RegistryKeyClass Create(string hkeyPath, EActivationParameter enableFunction, string allowText, RegistryValueKind valueKind, ERegistryHkey hkey = ERegistryHkey.LOCALMACHINE)
 {
     return(new RegistryKeyClass(hkeyPath, enableFunction, allowText, valueKind, hkey));
 }
Esempio n. 58
0
 internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
                                          int Reserved, RegistryValueKind dwType, String lpData, int cbData);
Esempio n. 59
0
        /// <summary>
        /// Retrieves the part of the sqlUserInstance.dll from the registry
        /// </summary>
        /// <param name="errorState">In case the dll path is not found, the error is set here.</param>
        /// <returns></returns>
        private string GetUserInstanceDllPath(out LocalDBErrorState errorState)
        {
            long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(s_className);

            try
            {
                string dllPath = null;
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(LocalDBInstalledVersionRegistryKey))
                {
                    if (key == null)
                    {
                        errorState = LocalDBErrorState.NO_INSTALLATION;
                        SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "No installation found.");
                        return(null);
                    }

                    Version zeroVersion = new Version();

                    Version latestVersion = zeroVersion;

                    foreach (string subKey in key.GetSubKeyNames())
                    {
                        Version currentKeyVersion;

                        if (!Version.TryParse(subKey, out currentKeyVersion))
                        {
                            errorState = LocalDBErrorState.INVALID_CONFIG;
                            SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "Invalid Configuration.");
                            return(null);
                        }

                        if (latestVersion.CompareTo(currentKeyVersion) < 0)
                        {
                            latestVersion = currentKeyVersion;
                        }
                    }

                    // If no valid versions are found, then error out
                    if (latestVersion.Equals(zeroVersion))
                    {
                        errorState = LocalDBErrorState.INVALID_CONFIG;
                        SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "Invalid Configuration.");
                        return(null);
                    }

                    // Use the latest version to get the DLL path
                    using (RegistryKey latestVersionKey = key.OpenSubKey(latestVersion.ToString()))
                    {
                        object instanceAPIPathRegistryObject = latestVersionKey.GetValue(InstanceAPIPathValueName);

                        if (instanceAPIPathRegistryObject == null)
                        {
                            errorState = LocalDBErrorState.NO_SQLUSERINSTANCEDLL_PATH;
                            SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "No SQL user instance DLL. Instance API Path Registry Object Error.");
                            return(null);
                        }

                        RegistryValueKind valueKind = latestVersionKey.GetValueKind(InstanceAPIPathValueName);

                        if (valueKind != RegistryValueKind.String)
                        {
                            errorState = LocalDBErrorState.INVALID_SQLUSERINSTANCEDLL_PATH;
                            SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.ERR, "Invalid SQL user instance DLL path. Registry value kind mismatch.");
                            return(null);
                        }

                        dllPath = (string)instanceAPIPathRegistryObject;

                        errorState = LocalDBErrorState.NONE;
                        return(dllPath);
                    }
                }
            }
            finally
            {
                SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID);
            }
        }
 /// <summary>
 /// 设置注册表启动项
 /// </summary>
 /// <param name="regeditName">注册表键</param>
 /// <param name="regeditValue">数据</param>
 /// <param name="valueKind">RegistryValueKind 枚举</param>
 /// <returns></returns>
 public static bool SetValueRun(string regeditName, object regeditValue, RegistryValueKind valueKind = RegistryValueKind.None)
 {
     return(SetValueLocalMachine(REGEDIT_KEY_RUN, regeditName, regeditValue, valueKind));
 }