/// <summary> /// /// </summary> /// <param name="root"></param> /// <param name="subKey"></param> internal static void CreateKey(RegistryKey root, string subKey) { RegistryKey rk = null; try { rk = root.CreateSubKey( subKey ); if ( rk != null ) { Log.AppendString( logfile, "Created key: " + rk.ToString() + Environment.NewLine ); Display.UpdateStatus( "Created: " + root.ToString() + "\\..." + subKey.Substring( subKey.LastIndexOf( '\\' ) ) + "\\*" ); } } catch ( Exception ex ) { // Record exceptions in the log file Log.AppendException( logfile, ex ); } finally { // Finally, cleanup and prepare variables for garbage collection if ( rk != null ) { rk.Close(); rk = null; } subKey = null; } }
/// <summary> /// 修改指定序号的网卡的MAC地址。 /// </summary> /// <param name="pAdapterIndex">网卡序号</param> /// <param name="pMacAddress">网卡MAC地址</param> /// <returns></returns> public static Boolean ModifyMacAddress(Int32 pAdapterIndex, string pMacAddress) { // 网卡序号从0开始 if (pAdapterIndex < 0) { throw new ApplicationException("无效的网卡序号!"); } string strIndex = pAdapterIndex.ToString().PadLeft(4, '0'); strIndex = strIndex.Substring(strIndex.Length - 4); // 网卡格式。长度为12。剔除里面的-或者: if (!String.IsNullOrEmpty(pMacAddress) && pMacAddress.Length > 0) { pMacAddress = pMacAddress.Trim().Replace(":", "").Replace("-", "").Replace(" ", ""); pMacAddress = pMacAddress.ToUpper(); } if (pMacAddress.Length > 0 && pMacAddress.Length != 12) { throw new ApplicationException("无效的MAC地址"); } Reg.RegistryKey regRoot = Reg.Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\" + strIndex, true); Reg.RegistryKey regParams = regRoot.OpenSubKey(@"Ndi\params\NetworkAddress", true); if (regParams != null) { string[] valNames = regRoot.GetValueNames(); //先删除 if (valNames.Contains("NetworkAddress")) { regRoot.DeleteValue("NetworkAddress"); regParams.SetValue("Default", ""); } if (!string.IsNullOrEmpty(pMacAddress) && pMacAddress.Length > 0) { regRoot.SetValue("NetworkAddress", pMacAddress); regParams.SetValue("Default", pMacAddress); } //Console.WriteLine(regRoot.GetValue("InfPath").ToString()); return(true); } else { throw new ApplicationException("没有找到键值:" + regParams.ToString()); } }
/// 搜索注册表指定项 /// <param name="key">注册表项</param> private void SearchRegistryKey(RegistryKey key) { if (key == null) return; //判断项是否为空 //获取注册表项的键名列表 string[] valueNames = key.GetValueNames(); //将注册表项加入到搜索状态提示中 SetSearchState(key.ToString()); //遍历所有键名,判断键名或键值中是否含有搜索的关键字 foreach (string valueName in valueNames) { //搜索的关键字 string keywords = tBKeywords.Text; //获取键值并转换成字符串类型 string value = key.GetValue(valueName).ToString(); //判断键名或键值中是否含有搜索的关键字 if (valueName.Contains(keywords) || value.Contains(keywords)) {//如果含有搜索关键字 //将该键在注册表中的全路径添加到搜索结果列表中 AddSearchState(key.ToString() + "\\" + valueName); } } //获取项的所有子项名 string[] subKeyNames = key.GetSubKeyNames(); //遍历所有子项,并对其进行搜索 foreach (string subKeyName in subKeyNames) { try { //根据子项名获取子项 RegistryKey subKey = key.OpenSubKey(subKeyName); //如果子项为空,则继续搜索下一子项 if (subKey == null) continue; //搜索子项 SearchRegistryKey(subKey); } catch (Exception) { //如果由于权限问题无法访问子项,则继续搜索下一子项 continue; } } key.Close(); }
public static OleDbConnection OpenDBConnection(RegistryKey regkey) { if (regkey==null) return null; OleDbConnection ret = null; string connectionString = string.Empty; string tmpStr = regkey.GetValue("Server") as string;; if (tmpStr == null) { MessageBox.Show ("Не определена группа ключей "+regkey.ToString()+"Server"); return ret; } try { if (tmpStr.Length>0) { // указан сервер, значит БД SQL connectionString = "Provider=SQLOLEDB; Server="+tmpStr+";" + "database="+regkey.GetValue("DBName").ToString()+";" + "Integrated Security=SSPI; Persist Security Info=false;"; } else { // не указан сервер, значит БД Access connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"+ "Data Source="+regkey.GetValue("DBName").ToString()+";"; } } catch{} ret = new OleDbConnection(connectionString); try { ret.Open(); } catch (Exception ex) { MessageBox.Show (ex.Message); ret = null; } return ret; }
private void EnumMRUList(RegistryKey regKey, string subkey = "") { foreach (string strValueName in regKey.GetValueNames()) { ProgressWorker.I.EnQ(string.Format("Scanning {0}\\{1}", regKey.ToString(), string.Empty)); string filePath, fileArgs; // Ignore MRUListEx and others if (!Regex.IsMatch(strValueName, "[0-9]")) continue; string fileName = ExtractUnicodeStringFromBinary(regKey.GetValue(strValueName)); string shortcutPath = string.Format("{0}\\{1}.lnk", Environment.GetFolderPath(Environment.SpecialFolder.Recent), fileName); // See if file exists in Recent Docs folder if (!string.IsNullOrEmpty(fileName)) { //ScanDlg.StoreInvalidKey(Strings.InvalidRegKey, regKey.ToString(), strValueName); this.BadKeys.Add(new InvalidKeys() { Root = Registry.CurrentUser, Subkey = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RecentDocs", Key = subkey != string.Empty ? subkey : string.Empty, Name = strValueName }); continue; } if (!File.Exists(shortcutPath) || !FileOperations.I.ResolveShortcut(shortcutPath, out filePath, out fileArgs)) { //ScanDlg.StoreInvalidKey(Strings.InvalidFile, regKey.ToString(), strValueName); this.BadKeys.Add(new InvalidKeys() { Root = Registry.CurrentUser, Subkey = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RecentDocs", Key = subkey != string.Empty ? subkey : string.Empty, Name = strValueName }); continue; } } }
void RecurseCopyKey(RegistryKey sourceKey, RegistryKey destinationKey) { Logger.LogInfo(String.Format("Copying from {0} to {1}", sourceKey.ToString(), destinationKey.ToString())); //copy all the values foreach (string valueName in sourceKey.GetValueNames()) { // Don't overwrite if (!ShouldExcludeKey(valueName) && destinationKey.GetValue(valueName) == null) { object objValue = sourceKey.GetValue(valueName); RegistryValueKind valKind = sourceKey.GetValueKind(valueName); destinationKey.SetValue(valueName, objValue, valKind); } else { Logger.LogInfo(String.Format("Skipping value {0} as it already exists in the destination key", valueName)); } } //For Each subKey //Create a new subKey in destinationKey //Call myself foreach (string sourceSubKeyName in sourceKey.GetSubKeyNames()) { using (RegistryKey sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName)) { using (RegistryKey destSubKey = destinationKey.CreateSubKey(sourceSubKeyName)) { RecurseCopyKey(sourceSubKey, destSubKey); } } } }
private bool ReadFromKey(RegistryKey root) { System.Diagnostics.Debug.Assert(m_keyString != null, "m_keyString was not set prior to reading from key"); System.Diagnostics.Debug.Assert(root.ToString().EndsWith(m_keyString), "m_keyString did not match root registry key suffix"); try { string serverName = root.GetValue("Server", "").ToString(); int port = (int)root.GetValue("Port", 0); string context = root.GetValue("Context", "").ToString(); string userName = root.GetValue("User", "").ToString(); string password = root.GetValue("Password", "").ToString(); root.Close(); Policy.Crypto crypt = Workshare.Policy.Crypto.Instance; if (!string.IsNullOrEmpty(userName)) { userName = crypt.DecryptData(userName); } if (!string.IsNullOrEmpty(password)) { password = crypt.DecryptData(password); } ServerName = serverName; Port = port; Context = context; UserName = userName; Password = password; } catch (SecurityException e) { Logger.LogError(@"Cannot access the registry key [" + root + "]. "); Logger.LogError(e); return false; } catch (UnauthorizedAccessException e) { Logger.LogError(@"Cannot access the registry key [" + root + "]. "); Logger.LogError(e); return false; } catch (SystemException e) { Logger.LogError(@"Failed to read the settings from the registry key [" + root + "]."); Logger.LogError(e); return false; } return true; }
/// <summary> /// Deletes a Registry key tree /// </summary> /// <param name="root"></param> /// <param name="subKey"></param> internal static void DeleteTree(RegistryKey root, string subKey) { RegistryKey rk = null; string fqKeyPath = null; try { rk = root.OpenSubKey( subKey ); if ( rk != null ) { fqKeyPath = rk.ToString(); iDeletedKeysCount += ( rk.SubKeyCount + 1 ); iDeletedValuesCount += rk.ValueCount; rk.Close(); rk = null; root.DeleteSubKeyTree( subKey ); if ( fqKeyPath != null ) { Log.AppendString( logfile, "Deleted tree: " + fqKeyPath + Environment.NewLine ); Display.UpdateStatus( "Deleted: " + root.ToString() + "\\..." + subKey.Substring( subKey.LastIndexOf( '\\' ) ) + "\\*", ConsoleColor.Red ); } } } catch ( Exception ex ) { // Record exceptions in the log file Log.AppendException( logfile, ex ); } finally { // Finally, cleanup and prepare variables for garbage collection if ( rk != null ) { rk.Close(); rk = null; } fqKeyPath = null; subKey = null; } }
public static object getRegistryConfSafe(RegistryKey key, String valueName, Object defaultValue, RegistryValueKind kind, bool create) { object retVal; try { retVal = key.GetValue(valueName); } catch (Exception e) { try { if (create) { Logger.GetInstance().Error("Unable to get registry value: " + key.ToString() + " " + valueName + " creating with default value:" + defaultValue); key.SetValue(valueName, defaultValue, kind); } } catch { Logger.GetInstance().Error("Unable to create registry value: " + key.ToString() + " " + valueName + " with default value:" + defaultValue); } retVal = defaultValue; } if (retVal == null) { retVal = defaultValue; try { if (create) { Logger.GetInstance().Error("Null registry value: " + key.ToString() + " " + valueName + " creating with default value:" + defaultValue); key.SetValue(valueName, defaultValue, kind); } } catch { Logger.GetInstance().Error("Unable to create null registry value: " + key.ToString() + " " + valueName + " with default value:" + defaultValue); } } return retVal; }
/// <summary> /// Verify that a specific user has access rights to a specific Registry Key /// </summary> /// <param name="userName">Name of the user to check for</param> /// <param name="root">Root key for the registry key</param> /// <param name="subKey">Registry key to check for</param> /// <param name="rights">Expected access rights</param> public static void VerifyRegistryKeyPermission(string userName, Microsoft.Win32.RegistryKey root, string subKey, RegistryRights rights) { RegistryKey registryKey = root.OpenSubKey(subKey); RegistrySecurity registrySecurity = registryKey.GetAccessControl(); AuthorizationRuleCollection accessRules = registrySecurity.GetAccessRules(true, true, typeof(NTAccount)); foreach (RegistryAccessRule accessRule in accessRules) { if (userName.ToLowerInvariant().Equals(accessRule.IdentityReference.Value.ToLowerInvariant())) { if ((accessRule.RegistryRights & rights) == rights) { return; } } } Assert.True(false, string.Format("User '{0}' do not have the correct permessions to RegistryKey '{1}/{2}'.", userName, root.ToString(), subKey)); }
/// <summary> /// Returns all values from registry path, using specified Registry key /// </summary> /// <param name="path">path to registry key beginning </param> /// <returns>Dictionary w/ values or empty</returns> public static Dictionary<string, object> GetAllValues(RegistryKey rootKey, string path) { Dictionary<string, object> arValues = new Dictionary<string, object>(); //KeyValuePair<string, object>[] arValues1 = null; string[] arKeys = null; //string subPath = ""; RegistryKey key = null; //RegistryKey rootKey = Registry.CurrentUser; if(path == null) { Log4cs.Log("No path specified for Registry!", Importance.Error); return arValues; } if(path.StartsWith("\\")) path = path.Substring(1); Log4cs.Log("Get values from: {0}\\{1}", rootKey.ToString(), path); try { key = rootKey.OpenSubKey(path); arKeys = key.GetValueNames(); Log4cs.Log(Importance.Debug, "Got " + arKeys.Length + " values in {0}\\{1}", rootKey.ToString(), path); if(arKeys.Length > 0) { for(int i = 0; i < arKeys.Length; i++) { try { arValues[arKeys[i]] = key.GetValue(arKeys[i]).ToString(); } catch(Exception) { Log4cs.Log(Importance.Warning, "Duplicate key [" + arKeys[i] + "]"); } //Log4cs.Log("\t" + arKeys[i] + "->" + key.GetValue( arKeys[i] ).ToString() ); } } // END IF } catch(Exception ex) { Log4cs.Log(Importance.Error, "Error listing " + rootKey.ToString() + "\\" + path); Log4cs.Log(Importance.Debug, ex.ToString()); //return m_arValues; } try { key.Close(); rootKey.Close(); } catch(Exception) { } return arValues; }
public RegistryReader(RegistryKey key) { mKey = key; string s = key.ToString(); baseName = s.Substring(s.LastIndexOf("\\") + 1); }
protected void ShowErrorMessage(Exception e, string operation, RegistryKey baseRegistryKey, string subKeyPath, string keyName) { ShowErrorMessage(e, operation + " [" + baseRegistryKey.ToString() + @"\" + subKeyPath + @"\" + (keyName == null ? "" : keyName.ToUpper()) + "]"); }
protected override void Check(MainForm form, string ext, RegistryKey rk, DataEntry[] de) { bool openWith = false; bool imagePreview = false; string progid = CheckStringValue(form, rk, null, de); if (!string.IsNullOrEmpty(progid)) { using (RegistryKey r = OpenSubKey(form, rk, "OpenWithProgids", de)) { if (r != null) { if (Array.IndexOf(r.GetValueNames(), progid) < 0) { form.Add(this, Resources.MissingRegistryValue, de, new DataEntry(Resources.Value, progid), new DataEntry(Resources.Key, rk.ToString())); } } } using (RegistryKey r = OpenSubKey(form, rk, string.Format(CultureInfo.InvariantCulture, "OpenWithList\\{0}", PhotoViewerDll), de, ref openWith)) { } using (RegistryKey r = OpenSubKey(form, rk, "ShellExt\\ContextMenuHandlers\\ShellImagePreview", de, ref imagePreview)) { CheckValue(form, r, null, new string[] { PhotoGalleryGuid }, de); } using (RegistryKey r = OpenSubKey(form, Registry.ClassesRoot, progid, new DataEntry[0])) { CheckStringValue(form, r, null, de); using (RegistryKey r1 = OpenSubKey(form, r, "DefaultIcon", new DataEntry[0])) { string iconPath = CheckStringValue(form, r1, null, de); if (!string.IsNullOrEmpty(iconPath)) { using (TempFileCollection t = new TempFileCollection()) { string file = t.AddExtension(ext); File.WriteAllBytes(file, new byte[0]); try { Icon.ExtractAssociatedIcon(file).Dispose(); } catch (Exception e) { form.Add(this, Resources.CannotExtractIcon, de, new DataEntry(Resources.Key, r1.ToString()), new DataEntry(Resources.Value, Resources.RegistryValue_default), new DataEntry(Resources.Actual, iconPath), new DataEntry(e)); } } } } using (RegistryKey r1 = OpenSubKey(form, r, "shell\\open\\command", new DataEntry[0])) { CheckValue(form, r1, null, new string[] { string.Format(CultureInfo.InvariantCulture, "%SystemRoot%\\System32\\rundll32.exe \"{0}\", ImageView_Fullscreen %1", PhotoGalleryPath) }, de); } using (RegistryKey r1 = OpenSubKey(form, r, "shell\\open", new DataEntry[0])) { CheckValue(form, r1, "MuiVerb", new string[] { string.Format(CultureInfo.InvariantCulture, "@{0},-3043", PhotoGalleryPath) }, de); } using (RegistryKey r1 = OpenSubKey(form, r, "shell\\open\\DropTarget", new DataEntry[0])) { CheckValue(form, r1, "Clsid", new string[] { PhotoGalleryGuid }, de); } using (RegistryKey r1 = OpenSubKey(form, r, "shell\\printto\\command", new DataEntry[0])) { CheckValue(form, r1, null, new string[] { "%SystemRoot%\\System32\\rundll32.exe \"%SystemRoot%\\System32\\shimgvw.dll\", ImageView_PrintTo /pt \"%1\" \"%2\" \"%3\" \"%4\"" }, de); } } } using (RegistryKey r = OpenSubKey(form, Registry.ClassesRoot, string.Format(CultureInfo.InvariantCulture, "SystemFileAssociations\\{0}", ext), new DataEntry[0])) { using (RegistryKey r1 = OpenSubKey(form, r, string.Format(CultureInfo.InvariantCulture, "OpenWithList\\{0}", PhotoViewerDll), de, ref openWith)) { } using (RegistryKey r2 = OpenSubKey(form, r, "ShellEx\\ContextMenuHandlers\\ShellImagePreview", de, ref imagePreview)) { CheckValue(form, r2, null, new string[] { PhotoGalleryGuid }, de); } } if (!openWith) { form.Add(this, Resources.MissingRegistryKey, de, new DataEntry(Resources.Key, new string[] { string.Format(CultureInfo.InvariantCulture, "{2}\\{0}\\OpenWithList\\{1}", ext, PhotoViewerDll, Registry.ClassesRoot), string.Format(CultureInfo.InvariantCulture, "{2}\\SystemFileAssociations\\{0}\\OpenWithList\\{1}", ext, PhotoViewerDll, Registry.ClassesRoot) })); } if (!imagePreview) { form.Add(this, Resources.MissingRegistryKey, de, new DataEntry(Resources.Key, new string[] { string.Format(CultureInfo.InvariantCulture, "{2}\\{0}\\ShellEx\\ContextMenuHandlers\\ShellImagePreview", ext, PhotoViewerDll, Registry.ClassesRoot), string.Format(CultureInfo.InvariantCulture, "{2}\\SystemFileAssociations\\{0}\\ShellEx\\ContextMenuHandlers\\ShellImagePreview", ext, PhotoViewerDll, Registry.ClassesRoot) })); } }
public static void setRegistryConfSafe(RegistryKey key, String valueName, Object newValue, RegistryValueKind kind) { try { key.SetValue(valueName, newValue, kind); } catch (Exception e) { Logger.GetInstance().Error("Unable to set registry value: " + key.ToString() + " " + valueName + " to:" + newValue); } }
protected override void Check(ListView.ListViewItemCollection collection, string ext, RegistryKey rk, IWICBitmapDecoderInfo info) { DataEntry[] de = new DataEntry[] { new DataEntry("File Extension", ext)}; string progid = CheckStringValue(collection, rk, null, de); if (!string.IsNullOrEmpty(progid)) { using (RegistryKey r = OpenSubKey(collection, rk, "OpenWithProgids", de)) { if (r != null) { if (Array.IndexOf(r.GetValueNames(), progid) < 0) { collection.Add(this, "Registry value is missing.", de, new DataEntry("Expected Values", progid), new DataEntry("Key", rk.ToString())); } } } using (RegistryKey r = OpenSubKey(collection, rk, string.Format(CultureInfo.InvariantCulture, "OpenWithList\\{0}", PhotoViewerDll), de)) { } using (RegistryKey r = OpenSubKey(collection, rk, "ShelExt\\ContextMenuHandlers\\ShellImagePreview", de)) { CheckValue(collection, r, null, new string[] { PhotoGalleryGuid }, de); } using (RegistryKey r = OpenSubKey(collection, Registry.ClassesRoot, progid, new DataEntry[0])) { CheckStringValue(collection, r, null, de); using (RegistryKey r1 = OpenSubKey(collection, r, "DefaultIcon", new DataEntry[0])) { CheckStringValue(collection, r1, null, de); // TODO get and check icon } using (RegistryKey r1 = OpenSubKey(collection, r, "shell\\open\\command", new DataEntry[0])) { CheckValue(collection, r1, null, new string []{"%SystemRoot%\\System32\\rundll32.exe \"%ProgramFiles%\\Windows Photo Gallery\\PhotoViewer.dll\", ImageView_Fullscreen %1"}, de); } using (RegistryKey r1 = OpenSubKey(collection, r, "shell\\open", new DataEntry[0])) { CheckValue(collection, r1, "MuiVerb", new string[] { "@%ProgramFiles%\\Windows Photo Gallery\\PhotoViewer.dll,-3043" }, de); } using (RegistryKey r1 = OpenSubKey(collection, r, "shell\\open\\DropTarget", new DataEntry[0])) { CheckValue(collection, r1, "Clsid", new string[] { PhotoGalleryGuid }, de); } using (RegistryKey r1 = OpenSubKey(collection, r, "shell\\printto\\command", new DataEntry[0])) { CheckValue(collection, r1, null, new string[] { "%SystemRoot%\\System32\\rundll32.exe \"%ProgramFiles%\\Windows Photo Gallery\\PhotoViewer.dll\", ImageView_PrintTo /pt \"%1\" \"%2\" \"%3\" \"%4\"" }, de); } } } using (RegistryKey r = OpenSubKey(collection, Registry.ClassesRoot, string.Format(CultureInfo.InvariantCulture, "SystemFileAssociations\\{0}", ext), new DataEntry[0])) { using (RegistryKey r2 = OpenSubKey(collection, r, "ShellEx\\ContextMenuHandlers\\ShellImagePreview", de)) { CheckValue(collection, r2, null, new string[] { PhotoGalleryGuid }, de); } } }
/// <summary> /// Delete all values found in a Registry key. /// </summary> /// <param name="key">Registry Key Path</param> internal static void DeleteAllValues(RegistryKey root, string subKey) { RegistryKey rk = null; string[] valueNames = null; try { rk = root.OpenSubKey( subKey, true ); if ( rk != null ) { // Retain a list of value names for this key valueNames = rk.GetValueNames(); // Return to caller if no values are found if ( valueNames != null && valueNames.Length != 0 ) { // Delete each value in this key foreach ( string valueName in valueNames ) { rk.DeleteValue( valueName ); iDeletedValuesCount++; Log.AppendString( logfile, "Deleted value: " + rk.ToString() + "\\" + valueName + Environment.NewLine ); Display.UpdateStatus( "Deleted: " + root.ToString() + "\\...\\" + valueName, ConsoleColor.Red ); } } } } catch ( Exception ex ) { // Record exceptions in the log file Log.AppendException( logfile, ex ); } finally { // Finally, cleanup and prepare variables for garbage collection if ( rk != null ) { rk.Close(); rk = null; } valueNames = null; subKey = null; } }
/// <summary> /// Writes a byte[] value to key /// </summary> /// <param name="key">Registry Key Path</param> /// <param name="value">32-bit binary value</param> internal static void SetValue(RegistryKey root, string subKey, string name, byte[] value) { RegistryKey rk = null; try { rk = root.OpenSubKey( subKey, true ); if ( rk != null ) { rk.SetValue( name, value, RegistryValueKind.Binary ); iAlteredValuesCount++; //Log.AppendString( logfile, "Set value: " + rk.ToString() + "\\" + name + " = " + value + Environment.NewLine ); Display.UpdateStatus( "Changed: " + root.ToString() + "\\...\\" + name + " = [BINARY]" ); } } catch ( Exception ex ) { Log.AppendException( logfile, ex ); } finally { if ( rk != null ) { rk.Close(); rk = null; } subKey = null; name = null; } }
public static int createMultiKey() { addLog("########### createMultiKey #################"); int iRet = -1; ITC_KEYBOARD.CUSBkeys _cusb = new ITC_KEYBOARD.CUSBkeys(); //get current keyboard mapping reg location string sReg = ITC_KEYBOARD.CUSBkeys.getRegLocation(); //count Multikey entries, remember: Multikey numbering starts by 1 (not zero)! addLog("Opening subkey '" + sReg + "\\Multikeys'..."); Microsoft.Win32.RegistryKey reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sReg + "\\Multikeys", true); int iNumKeys = reg.ValueCount; addLog("Found " + iNumKeys.ToString() + " value entries"); #region usbkeys //we need two entries in the last, new reg entry //one to fire a vkey: //one to fire an named event ITC_KEYBOARD.CUSBkeys.usbKeyStruct _usbKeyVKEY = new CUSBkeys.usbKeyStruct(); _usbKeyVKEY.bFlagHigh = CUsbKeyTypes.usbFlagsHigh.NoFlag; _usbKeyVKEY.bFlagMid = CUsbKeyTypes.usbFlagsMid.VKEY | CUsbKeyTypes.usbFlagsMid.NoRepeat; _usbKeyVKEY.bFlagLow = CUsbKeyTypes.usbFlagsLow.NormalKey; _usbKeyVKEY.bIntScan = (byte)ITC_KEYBOARD.VKEY.undef_0x88; //use vkey=0x88 byte[] bytesVKey = { (byte)_usbKeyVKEY.bFlagHigh, (byte)_usbKeyVKEY.bFlagMid, (byte)_usbKeyVKEY.bFlagLow, (byte)_usbKeyVKEY.bIntScan }; ITC_KEYBOARD.CUSBkeys.usbKeyStruct _usbKeyEVENT = new CUSBkeys.usbKeyStruct(); _usbKeyEVENT.bFlagHigh = CUsbKeyTypes.usbFlagsHigh.NoFlag; _usbKeyEVENT.bFlagMid = CUsbKeyTypes.usbFlagsMid.NoRepeat | CUsbKeyTypes.usbFlagsMid.VKEY; _usbKeyEVENT.bFlagLow = CUsbKeyTypes.usbFlagsLow.NormalKey; _usbKeyEVENT.bIntScan = 0x88; byte[] bytesEventKey = { (byte)_usbKeyEVENT.bFlagHigh, (byte)_usbKeyEVENT.bFlagMid, (byte)_usbKeyEVENT.bFlagLow, (byte)_usbKeyEVENT.bIntScan }; byte[] bytesAll = new byte[bytesVKey.Length + bytesEventKey.Length]; System.Buffer.BlockCopy(bytesVKey, 0, bytesAll, 0, bytesVKey.Length); System.Buffer.BlockCopy(bytesEventKey, 0, bytesAll, bytesVKey.Length, bytesEventKey.Length); #endregion //check if the mutlikey is already in place string sValueName = "Multi" + iNumKeys.ToString(""); byte[] bValues = null; try { bValues = (byte[])reg.GetValue(sValueName, null); addLog("GetValue last multikey ('" + sValueName + "') OK"); } catch (Exception ex) { addLog("GetValue last multikey ('" + sValueName + "') failed" + ex.Message); } //write new mutlikey? if (bValues != null) { if (!compareBytes(bValues, bytesAll)) { //create a new entry try { reg.SetValue("Multi" + (iNumKeys + 1).ToString(), bytesAll, Microsoft.Win32.RegistryValueKind.Binary); addLog("Creating new multikey value OK: " + reg.ToString()); } catch (Exception ex) { addLog("Creating new multikey value failed" + ex.Message); } } } //change the scanner key to point to the new multikey index mapScanKey2Multi((byte)(iNumKeys + 1)); addLog("----------- createMultiKey -----------------"); reg.Close(); return(iRet); }
private static void doFoundWinRegKey(RegistryKey rCore, StringBuilder logger) { doLogSetEnvVarInfo(string.Format("Found Windows registry key {0}", rCore.ToString()), logger); }
public static void Win32RegValueKind(RegistryKey hKey, string sValue, SubKeyValueInfo keyValueInfo) { string sDataType = string.Empty; StringBuilder sbTemp = new StringBuilder(); keyValueInfo.sData = string.Empty; keyValueInfo.sDataBuf = null; object sDataBuf = null; int type; RegistryValueKind valueKind = hKey.GetValueKind(sValue); switch (valueKind) { case RegistryValueKind.Unknown: keyValueInfo.RegDataType = LWRegistryValueKind.REG_RESOURCE_LIST; string[] sKey = hKey.ToString().Split(new char[] { '\\' } , 2); sDataBuf = RegGetValue(GetRegistryHive(keyValueInfo.hKey), sKey[1], sValue, out type); keyValueInfo.intDataType = type; if (sDataBuf != null) { byte[] sBinaryData = sDataBuf as byte[]; foreach (byte byt in sBinaryData) { string stringValue = BitConverter.ToString(new byte[] { byt }); if (stringValue.Length == 1) stringValue = "0" + stringValue; sbTemp.Append(stringValue); sbTemp.Append(" "); } keyValueInfo.sData = sbTemp.ToString(); } break; case RegistryValueKind.Binary: keyValueInfo.RegDataType = LWRegistryValueKind.REG_BINARY; sDataBuf = hKey.GetValue(sValue, null, RegistryValueOptions.DoNotExpandEnvironmentNames); if (sDataBuf != null) { byte[] sBinaryData = sDataBuf as byte[]; if (sBinaryData != null) { foreach (byte byt in sBinaryData) { string stringValue = BitConverter.ToString(new byte[] { byt }); if (stringValue.Length == 1) stringValue = "0" + stringValue; sbTemp.Append(stringValue); sbTemp.Append(" "); } } } keyValueInfo.sData = sbTemp.ToString(); break; case RegistryValueKind.DWord: keyValueInfo.RegDataType = LWRegistryValueKind.REG_DWORD; keyValueInfo.sDataBuf = hKey.GetValue(sValue, null, RegistryValueOptions.DoNotExpandEnvironmentNames); if (keyValueInfo.sDataBuf != null) { string sTemp = keyValueInfo.sDataBuf.ToString(); sTemp = RegistryUtils.DecimalToBase((UInt32)Convert.ToInt32(keyValueInfo.sDataBuf), 16); keyValueInfo.sData = string.Concat("0x", sTemp.PadLeft(8,'0'), "(", ((uint)Convert.ToInt32(keyValueInfo.sDataBuf)).ToString(), ")"); } break; case RegistryValueKind.ExpandString: keyValueInfo.RegDataType = LWRegistryValueKind.REG_EXPAND_SZ; sDataBuf = hKey.GetValue(sValue, null, RegistryValueOptions.DoNotExpandEnvironmentNames); if (sDataBuf != null) { keyValueInfo.sData = sDataBuf.ToString(); } break; case RegistryValueKind.MultiString: keyValueInfo.RegDataType = LWRegistryValueKind.REG_MULTI_SZ; sDataBuf = hKey.GetValue(sValue, null, RegistryValueOptions.DoNotExpandEnvironmentNames); if (sDataBuf != null) { string[] sStringData = sDataBuf as string[]; if (sStringData != null) { foreach (string sr in sStringData) { sbTemp.Append(sr); sbTemp.Append(" "); } } } keyValueInfo.sData = sbTemp.ToString(); break; case RegistryValueKind.QWord: keyValueInfo.RegDataType = LWRegistryValueKind.REG_QUADWORD; sDataBuf = hKey.GetValue(sValue, null, RegistryValueOptions.DoNotExpandEnvironmentNames); if (sDataBuf != null) { string sTemp = sDataBuf.ToString(); sTemp = RegistryUtils.DecimalToBase((UInt64)Convert.ToInt64(sDataBuf), 16); keyValueInfo.sData = string.Concat("0x", sTemp.PadLeft(16,'0'), "(", ((ulong)Convert.ToInt64(sDataBuf)).ToString(), ")"); } break; case RegistryValueKind.String: keyValueInfo.RegDataType = LWRegistryValueKind.REG_SZ; sDataBuf = hKey.GetValue(sValue, null, RegistryValueOptions.DoNotExpandEnvironmentNames); if (sDataBuf != null) { keyValueInfo.sData = sDataBuf.ToString(); } break; default: keyValueInfo.RegDataType = LWRegistryValueKind.REG_NONE; sDataBuf = hKey.GetValue(sValue, null, RegistryValueOptions.DoNotExpandEnvironmentNames); if (sDataBuf != null) keyValueInfo.sData = sDataBuf.ToString(); else keyValueInfo.sData = "(zero-length binary value)"; break; } }
private void ValidateExplorerExt(RegistryKey regKey) { try { // Sees if icon file exists string strHotIcon = regKey.GetValue("HotIcon") as string; if (!string.IsNullOrEmpty(strHotIcon)) { if (!FileOperations.IconExists(strHotIcon)) { //ScanDlg.StoreInvalidKey(Strings.InvalidFile, regKey.ToString(), "HotIcon"); string key = regKey.ToString(); key = key.Substring(key.IndexOf('\\') + 1); this.BadKeys.Add(new InvalidKeys() { Root = Registry.LocalMachine, Subkey = key, Key = string.Empty, Name = strHotIcon }); } } string strIcon = regKey.GetValue("Icon") as string; if (!string.IsNullOrEmpty(strIcon)) { if (!FileOperations.IconExists(strIcon)) { //ScanDlg.StoreInvalidKey(Strings.InvalidFile, regKey.ToString(), "Icon"); string key = regKey.ToString(); key = key.Substring(key.IndexOf('\\') + 1); this.BadKeys.Add(new InvalidKeys() { Root = Registry.LocalMachine, Subkey = key, Key = string.Empty, Name = "Icon" }); } } // Lookup CLSID extension string strClsidExt = regKey.GetValue("ClsidExtension") as string; if (!string.IsNullOrEmpty(strClsidExt)) { //ScanDlg.StoreInvalidKey(Strings.MissingCLSID, regKey.ToString(), "ClsidExtension"); string key = regKey.ToString(); key = key.Substring(key.IndexOf('\\') + 1); this.BadKeys.Add(new InvalidKeys() { Root = Registry.LocalMachine, Subkey = key, Key = string.Empty, Name = "ClsidExtension" }); } // See if files exist string strExec = regKey.GetValue("Exec") as string; if (!string.IsNullOrEmpty(strExec)) { if (!FileOperations.FileExists(strExec)) { //ScanDlg.StoreInvalidKey(Strings.InvalidFile, regKey.ToString(), "Exec"); string key = regKey.ToString(); key = key.Substring(key.IndexOf('\\') + 1); this.BadKeys.Add(new InvalidKeys() { Root = Registry.LocalMachine, Subkey = key, Key = string.Empty, Name = "Exec" }); } } string strScript = regKey.GetValue("Script") as string; if (!string.IsNullOrEmpty(strScript)) { if (!FileOperations.FileExists(strScript)) { //ScanDlg.StoreInvalidKey(Strings.InvalidFile, regKey.ToString(), "Script"); string key = regKey.ToString(); key = key.Substring(key.IndexOf('\\') + 1); this.BadKeys.Add(new InvalidKeys() { Root = Registry.LocalMachine, Subkey = key, Key = string.Empty, Name = "Script" }); } } } catch (SecurityException ex) { Debug.WriteLine(ex.Message); } }
public static Dictionary<string, Dictionary<string, object>> GetAllSubKeysValues(RegistryKey rootKey, string path) { Dictionary<string, Dictionary<string, object>> arDict = new Dictionary<string, Dictionary<string, object>>(); Dictionary<string, object> arValues = new Dictionary<string, object>(); //string[] arKeys = null; //string subPath = ""; RegistryKey key = null; if(path == null) { Log4cs.Log("No path specified for Registry!", Importance.Error); return null; } if(path.StartsWith("\\")) path = path.Substring(1); Log4cs.Log("Get subkeys from: {0}\\{1}", rootKey.ToString(), path); try { key = rootKey.OpenSubKey(path); string[] arSubKeys = key.GetSubKeyNames(); for(int i = 0; (arSubKeys != null) && (i < arSubKeys.Length); i++) { //Log4cs.Log(Importance.Debug, "\t" + arSubKeys[i]); arDict[arSubKeys[i]] = RegHelper.GetAllValues(rootKey, path + "\\" + arSubKeys[i]); } } catch(Exception ex) { Log4cs.Log(Importance.Error, "Error listing " + rootKey.ToString() + "\\" + path); Log4cs.Log(Importance.Debug, ex.ToString()); arDict = null; } try { key.Close(); rootKey.Close(); } catch(Exception) { } return arDict; }
void copyipv6address(RegistryKey source, uint luidindex, uint iftype, RegistryKey dest) { if (source == null) { Trace.WriteLine("No IPv6 Config found"); return; } //Construct a NET_LUID & convert to a hex string ulong prefixval = (((ulong)iftype) << 48) | (((ulong)luidindex) << 24); // Fix endianness to match registry entry & convert to string byte[] prefixbytes = BitConverter.GetBytes(prefixval); Array.Reverse(prefixbytes); string prefixstr = BitConverter.ToInt64(prefixbytes,0).ToString("x16"); Trace.WriteLine("Looking for prefix "+prefixstr); string[] keys = source.GetValueNames(); foreach (string key in keys) { Trace.WriteLine("Testing "+key); if (key.StartsWith(prefixstr)) { Trace.WriteLine("Found "+key); //Replace prefix with IPv6_Address____ before saving string newstring="IPv6_Address____"+key.Substring(16); Trace.WriteLine("Writing to " + dest.ToString()+" "+newstring); dest.SetValue(newstring, source.GetValue(key)); } } Trace.WriteLine("Copying addresses with prefix "+prefixstr+" done"); }
private void Load( RegistryKey root ) { { string pathList = root.ToString(); var permission = new RegistryPermission( RegistryPermissionAccess.Read, AccessControlActions.View, pathList ); permission.Demand(); } IEnumerable<IConfigurationSection> sections = GetSections( root ); sections.ToList().ForEach( Add ); }
/// <summary> /// Delete a value /// </summary> /// <param name="key">Registry Key Path</param> internal static void DeleteValue(RegistryKey root, string subKey, string name) { RegistryKey rk = null; try { rk = root.OpenSubKey( subKey, true ); if ( rk != null ) { rk.DeleteValue( name ); iAlteredValuesCount++; Log.AppendString( logfile, "Deleted value: " + rk.ToString() + "\\" + name + Environment.NewLine ); Display.UpdateStatus( "Deleted: " + root.ToString() + "\\...\\" + name, ConsoleColor.Red ); } } catch ( Exception ex ) { Log.AppendException( logfile, ex ); } finally { if ( rk != null ) { rk.Close(); rk = null; } subKey = null; name = null; } }
private static string GetRInstallPathFromRCoreKegKey(RegistryKey rCoreKey, StringBuilder logger) { string installPath = null; string[] subKeyNames = rCoreKey.GetSubKeyNames(); string[] valueNames = rCoreKey.GetValueNames(); if (valueNames.Length == 0) { doLogSetEnvVarWarn("Did not find any value names under " + rCoreKey, logger); return RecurseFirstSubkey(rCoreKey, logger); } else { const string installPathKey = "InstallPath"; if (valueNames.Contains(installPathKey)) { doLogSetEnvVarInfo("Found sub-key InstallPath under " + rCoreKey, logger); installPath = (string)rCoreKey.GetValue(installPathKey); } else { doLogSetEnvVarInfo("Did not find sub-key InstallPath under " + rCoreKey, logger); if (valueNames.Contains("Current Version")) { doLogSetEnvVarInfo("Found sub-key Current Version under " + rCoreKey, logger); string currentVersion = GetRCurrentVersionStringFromRegistry(rCoreKey); if (subKeyNames.Contains(currentVersion)) { var rVersionCoreKey = rCoreKey.OpenSubKey(currentVersion); return GetRInstallPathFromRCoreKegKey(rVersionCoreKey, logger); } else { doLogSetEnvVarWarn("Sub key "+ currentVersion + " not found in " + rCoreKey, logger); } } else { doLogSetEnvVarInfo("Did not find sub-key Current Version under " + rCoreKey, logger); return RecurseFirstSubkey(rCoreKey, logger); } } } doLogSetEnvVarInfo(string.Format("InstallPath value of key " + rCoreKey.ToString() + ": {0}", installPath == null ? "null" : installPath), logger); return installPath; }
///The problem with recursing over the registry to save the keys and values one at a time, is that the types provided by the ///RegistryValueKind enum are not explicits enough. For example, if we write in a file RegistryValueKind.MultiString.ToString() ///and then the value, we will obtain something like MultiString:"blah blah blah", while in a proper registry export we SHOULD HAVE /// hex(7):"blah blah blah". So we should include here a lot of pInvoke() calls to the win32 API to obtain the functions that could /// identify those types to write them to a file. /// SOLUTION: Use the regedit executable, which does this better than me, and it's present in every windows machine. /// ///regedit syntax is in the form: ///TO EXPORT: regedit.exe /E filetowrite.reg "ROOT_KEY_TO_EXPORT" ///TO IMPORT: regedit.exe /I /S file.reg //Saves a registry tree with root rootkey to disk public void exportRegTreetoDisk(RegistryKey rootkey, string filePath) { //Construct arguments string string arguments = "/E " + filePath + " \"" + rootkey.ToString() + "\" "; //Create the process Process prexport = new Process(); prexport.StartInfo.FileName = "regedit.exe"; prexport.StartInfo.UseShellExecute = false; prexport.StartInfo.Arguments = arguments; //Launch the process try { log("Backing up registry subtree: " + "\"" + rootkey.ToString() + "\" -----> " + filePath); prexport.Start(); prexport.WaitForExit(); } catch(Exception w) { logsub("Unexpected error while backing up the registry."); log(w.Message); throw (w); } finally { prexport.Dispose(); } logsub("Success..."); }
private void ValidateFileExt(RegistryKey regKey) { bool bProgidExists = false, bAppExists = false; // Skip if UserChoice subkey exists if (regKey.OpenSubKey("UserChoice") != null) return; // Parse and verify OpenWithProgId List using (RegistryKey rkProgids = regKey.OpenSubKey("OpenWithProgids")) { if (rkProgids != null) { foreach (string strProgid in rkProgids.GetValueNames()) { if (progIDExists(strProgid)) bProgidExists = true; } } } // Check if files in OpenWithList exist using (RegistryKey rkOpenList = regKey.OpenSubKey("OpenWithList")) { if (rkOpenList != null) { foreach (string strValueName in rkOpenList.GetValueNames()) { if (strValueName == "MRUList") continue; string strApp = rkOpenList.GetValue(strValueName) as string; if (appExists(strApp)) bAppExists = true; } } } if (!bProgidExists && !bAppExists) { //ScanDlg.StoreInvalidKey(Strings.InvalidFileExt, regKey.ToString()); string key = regKey.ToString(); key = key.Substring(key.IndexOf('\\') + 1); this.BadKeys.Add(new InvalidKeys() { Root = Registry.CurrentUser, Subkey = key, Key = string.Empty, Name = string.Empty }); } return; }
internal static Version ReadVersionValue(RegistryKey mshsnapinKey, string name, bool mandatory) { string temp = ReadStringValue(mshsnapinKey, name, mandatory); if (temp == null) { s_mshsnapinTracer.TraceError("Cannot read value for property {0} in registry key {1}", name, mshsnapinKey.ToString()); Dbg.Assert(!mandatory, "mandatory is true, ReadStringValue should have thrown exception"); return null; } Version v; try { v = new Version(temp); } catch (ArgumentOutOfRangeException) { s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } catch (ArgumentException) { s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } catch (OverflowException) { s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } catch (FormatException) { s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } s_mshsnapinTracer.WriteLine("Successfully converted string {0} to version format.", v); return v; }
protected void SetRegistryValue(RegistryKey root, string subkey, string key, string value) { try { string reg; value = value.Replace("\\", "\\\\"); reg = "Windows Registry Editor Version 5.00" + Environment.NewLine + Environment.NewLine + "[" + root.ToString() + "\\" + subkey + "]" + Environment.NewLine + "\"" + key + "\"=\"" + value + "\""; TextWriter tw = new StreamWriter(System.IO.Path.GetTempPath() + "GitExtensions.reg", false); tw.Write(reg); tw.Close(); GitCommands.GitCommands.RunCmd("regedit", "\"" + System.IO.Path.GetTempPath() + "GitExtensions.reg" + "\""); } catch (UnauthorizedAccessException ex) { MessageBox.Show("GitExtensions has insufficient permisions to modify the registry." + Environment.NewLine + "Please add this key to the registry manually." + Environment.NewLine + "Path: " + root.ToString() + "\\" + subkey + Environment.NewLine + "Value: " + key + " = " + value); } }
internal static Version ReadVersionValue(RegistryKey mshsnapinKey, string name, bool mandatory) { Version version; string str = ReadStringValue(mshsnapinKey, name, mandatory); if (str == null) { _mshsnapinTracer.TraceError("Cannot read value for property {0} in registry key {1}", new object[] { name, mshsnapinKey.ToString() }); return null; } try { version = new Version(str); } catch (ArgumentOutOfRangeException) { _mshsnapinTracer.TraceError("Cannot convert value {0} to version format", new object[] { str }); throw PSTraceSource.NewArgumentException("name", "MshSnapinInfo", "VersionValueInCorrect", new object[] { name, mshsnapinKey.Name }); } catch (ArgumentException) { _mshsnapinTracer.TraceError("Cannot convert value {0} to version format", new object[] { str }); throw PSTraceSource.NewArgumentException("name", "MshSnapinInfo", "VersionValueInCorrect", new object[] { name, mshsnapinKey.Name }); } catch (OverflowException) { _mshsnapinTracer.TraceError("Cannot convert value {0} to version format", new object[] { str }); throw PSTraceSource.NewArgumentException("name", "MshSnapinInfo", "VersionValueInCorrect", new object[] { name, mshsnapinKey.Name }); } catch (FormatException) { _mshsnapinTracer.TraceError("Cannot convert value {0} to version format", new object[] { str }); throw PSTraceSource.NewArgumentException("name", "MshSnapinInfo", "VersionValueInCorrect", new object[] { name, mshsnapinKey.Name }); } _mshsnapinTracer.WriteLine("Successfully converted string {0} to version format.", new object[] { version.ToString() }); return version; }