public GetValueKind ( string name ) : Microsoft.Win32.RegistryValueKind | ||
name | string | |
Результат | Microsoft.Win32.RegistryValueKind |
private static bool ReadRegistryValue(RegistryKey key, string valueName, bool defaultValue) { try { if (key.GetValueKind(valueName) == RegistryValueKind.DWord) { return Convert.ToBoolean(key.GetValue(valueName), CultureInfo.InvariantCulture); } } catch (UnauthorizedAccessException exception) { LogRegistryException("ReadRegistryValue", exception); } catch (IOException exception2) { LogRegistryException("ReadRegistryValue", exception2); } catch (SecurityException exception3) { LogRegistryException("ReadRegistryValue", exception3); } catch (ObjectDisposedException exception4) { LogRegistryException("ReadRegistryValue", exception4); } return defaultValue; }
private static bool ReadRegistryValue(RegistryKey key, string valueName, bool defaultValue) { Debug.Assert(key != null, "'key' must not be null"); try { // This check will throw an IOException if keyName doesn't exist. That's OK, we return the // default value. if (key.GetValueKind(valueName) == RegistryValueKind.DWord) { // At this point we know the Registry value exists and it must be valid (any DWORD value // can be converted to a bool). return Convert.ToBoolean(key.GetValue(valueName), CultureInfo.InvariantCulture); } } catch (UnauthorizedAccessException e) { LogRegistryException("ReadRegistryValue", e); } catch (IOException e) { LogRegistryException("ReadRegistryValue", e); } catch (SecurityException e) { LogRegistryException("ReadRegistryValue", e); } catch (ObjectDisposedException e) { LogRegistryException("ReadRegistryValue", e); } return defaultValue; }
private static string getStringValue(Microsoft.Win32.RegistryKey registrationSubKey, object registrationValue, string valueName, ref RegistryValueKind typeOfValue) { string valueStirng = String.Empty; typeOfValue = registrationSubKey.GetValueKind(valueName); try { switch (typeOfValue) { case RegistryValueKind.Binary: valueStirng = Convert.ToBase64String((byte[])registrationValue); break; case RegistryValueKind.String: valueStirng = registrationValue.ToString(); break; } } catch { } return(valueStirng); }
static PointF GetMonitorSizeUsingEDID(string targetInstanceName) { PointF pt = new PointF(); try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM WmiMonitorID"); foreach (ManagementObject queryObj in searcher.Get()) { dynamic code = queryObj["ProductCodeID"]; string pcid = ""; for (int i = 0; i < code.Length; i++) { pcid = pcid + Char.ConvertFromUtf32(code[i]); } float xSize = 0; float ySize = 0; string PNP = queryObj["InstanceName"].ToString(); PNP = PNP.Substring(0, PNP.Length - 2); // remove _0 if (PNP != null && PNP.Length > 0 && PNP.ToUpper() == targetInstanceName.ToUpper()) { string displayKey = "SYSTEM\\CurrentControlSet\\Enum\\"; string strSubDevice = displayKey + PNP + "\\" + "Device Parameters\\"; Microsoft.Win32.RegistryKey regKey = Registry.LocalMachine.OpenSubKey(strSubDevice, false); if (regKey != null) { if (regKey.GetValueKind("edid") == RegistryValueKind.Binary) { byte[] edid = (byte[])regKey.GetValue("edid"); const int edid_x_size_in_mm = 21; const int edid_y_size_in_mm = 22; xSize = ((float)edid[edid_x_size_in_mm] * 10f); ySize = ((float)edid[edid_y_size_in_mm] * 10f); pt.X = xSize; pt.Y = ySize; return(pt); } regKey.Close(); } } } } catch (ManagementException e) { Console.WriteLine("An error occurred while querying for WMI data: " + e.Message); return(new PointF(-1.0f, -1.0f)); } return(new PointF(-1.0f, -1.0f)); }
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); }
/// <summary> /// This constructor creates a named value from a Windows registry value /// </summary> /// <param name="key">Parent registry key</param> /// <param name="name">Name of the value</param> public RegValueEntry(RegistryKey key, string name) { Kind = MapNativeKindToRegis3Kind(key.GetValueKind(name)); Value = key.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames); Name = name; if (Value is string) { string temp = Value as string; if (temp.EndsWith("\0")) { Value = temp.Substring(0, temp.Length - 1); } } RemoveFlag = false; }
private static bool InnerCompare(RegistryKey A, RegistryKey B, string root,ref Dictionary<string, Data> output) { bool current = true; try { if (A != null) { // Process A foreach (var Name in A.GetValueNames()) { string EntryName = root + A.Name + "::" + Name; var dat = new Data(); dat.SetA(A.GetValue(Name), A.GetValueKind(Name)); output.Add(EntryName, dat); } foreach (var keyName in A.GetSubKeyNames()) { RegistryKey subA = A.OpenSubKey(keyName); RegistryKey subB = B == null ? null : B.OpenSubKey(keyName); current &= InnerCompare(subA, subB, root + keyName + @"\", ref output); } } if (B != null) { foreach (var Name in B.GetValueNames()) { string EntryName = root + B.Name + "::" + Name; Data dat = output.ContainsKey(EntryName) ? output[EntryName] : new Data(); dat.SetB(B.GetValue(Name), B.GetValueKind(Name)); output[EntryName] = dat; } foreach (var keyName in B.GetSubKeyNames()) { // when we get here, we have already cleared everything present in the A side RegistryKey subB = B.OpenSubKey(keyName); current &= InnerCompare(null, subB, root + keyName + @"\", ref output); } } return current; } catch (Exception e) { return false; } }
private static void RecurseCopyKey(RegistryKey sourceKey, RegistryKey destinationKey) { //copy all the values foreach (string valueName in sourceKey.GetValueNames()) { object objValue = sourceKey.GetValue(valueName); RegistryValueKind valKind = sourceKey.GetValueKind(valueName); destinationKey.SetValue(valueName, objValue, valKind); } //For Each subKey //Create a new subKey in destinationKey //Call myself foreach (string sourceSubKeyName in sourceKey.GetSubKeyNames()) { RegistryKey sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName); RegistryKey destSubKey = destinationKey.CreateSubKey(sourceSubKeyName); RecurseCopyKey(sourceSubKey, destSubKey); } }
private static string GetRegKeyValueAsString(RegistryKey key, string valueName) { string str = null; try { if (key.GetValueKind(valueName) == RegistryValueKind.String) { str = key.GetValue(valueName) as string; } } catch (ArgumentException) { } catch (IOException) { } catch (SecurityException) { } return str; }
private void RecurseCopyKey(RegistryKey sourceKey, RegistryKey destinationKey) { //copy all the values foreach (string valueName in sourceKey.GetValueNames()) { object objValue = sourceKey.GetValue(valueName); RegistryValueKind valKind = sourceKey.GetValueKind(valueName); destinationKey.SetValue(valueName, objValue, valKind); } //For Each subKey //Create a new subKey in destinationKey //Call myself foreach (string sourceSubKeyName in sourceKey.GetSubKeyNames()) { RegistryKey sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl); RegistryKey destSubKey = destinationKey.CreateSubKey(sourceSubKeyName, RegistryKeyPermissionCheck.ReadWriteSubTree); RecurseCopyKey(sourceSubKey, destSubKey); } }
public static Session getSession(RegistryKey registryKey) { var ret = new Session(); if (registryKey != null) { var valueKeys = registryKey.GetValueNames(); foreach (var key in valueKeys) { var value = new RegistryValue { kind = registryKey.GetValueKind(key), key = key, value = registryKey.GetValue(key).ToString() }; ret.Add(value); } } return ret; }
public bool TryGetComparisonValue(Microsoft.Win32.RegistryKey key, out string strValue) { strValue = null; // Get the key's value object tempObj = key.GetValue(ValueName); if (tempObj == null) { return(false); } strValue = tempObj.ToString(); // If the key is a binary key, get the byte array values in hex, and replace the dashes if (key.GetValueKind(ValueName) == RegistryValueKind.Binary) { byte[] value = (byte[])tempObj; string valueAsString = BitConverter.ToString(value); strValue = valueAsString.Replace("-", ""); } return(true); }
/// <summary> /// Gets the entries of a RegistryKey or value of a RegistryKey. /// </summary> /// <param name="RegHive">The RegistryHive to read from.</param> /// <param name="RegKey">The RegistryKey in the RegsitryHive to read from.</param> /// <param name="RegValue">The name of name/value pair to read from in the RegistryKey.</param> /// <returns>List of the entries of the RegistrySubKey or the RegistryValue, cast as a string.</returns> public static string GetRegistryKey(Win.RegistryHive RegHive, string RegKey, string RegValue) { Win.RegistryKey baseKey = null; switch (RegHive) { case Win.RegistryHive.CurrentUser: baseKey = Win.Registry.CurrentUser; break; case Win.RegistryHive.LocalMachine: baseKey = Win.Registry.LocalMachine; break; case Win.RegistryHive.ClassesRoot: baseKey = Win.Registry.ClassesRoot; break; case Win.RegistryHive.CurrentConfig: baseKey = Win.Registry.CurrentConfig; break; case Win.RegistryHive.Users: baseKey = Win.Registry.Users; break; default: baseKey = Win.Registry.CurrentUser; break; } string[] pieces = RegKey.Split(Path.DirectorySeparatorChar); for (int i = 0; i < pieces.Length; i++) { string[] valuenames = baseKey.GetValueNames(); string[] subkeynames = baseKey.GetSubKeyNames(); if (i == pieces.Length - 1 && valuenames.Contains(pieces[i], StringComparer.OrdinalIgnoreCase)) { string keyname = ""; for (int j = 0; j < pieces.Length - 1; j++) { keyname += pieces[j] + Path.DirectorySeparatorChar; } return(GetRegistryKeyValue(baseKey, pieces[i])); } if (!subkeynames.Contains(pieces[i], StringComparer.OrdinalIgnoreCase)) { return(null); } baseKey = baseKey.OpenSubKey(pieces[i]); } if (string.IsNullOrEmpty(RegValue)) { string output = "Key: " + RegHive.ToString() + "\\" + RegKey + Environment.NewLine; string[] valuenames = baseKey.GetValueNames(); string[] subkeynames = baseKey.GetSubKeyNames(); if (subkeynames.Any()) { output += "SubKeys:" + Environment.NewLine; } foreach (string subkeyname in subkeynames) { output += " " + subkeyname + Environment.NewLine; } if (valuenames.Any()) { output += "Values:"; } foreach (string valuename in valuenames) { output += Environment.NewLine; output += " Name: " + valuename + Environment.NewLine; output += " Kind: " + baseKey.GetValueKind(valuename).ToString() + Environment.NewLine; output += " Value: " + baseKey.GetValue(valuename) + Environment.NewLine; } return(output.Trim()); } return(GetRegistryKeyValue(baseKey, RegValue)); }
private static object ReadValue(RegistryKey r, string n) { if (r.GetValueKind(n) == RegistryValueKind.None) return null; return r.GetValue(n); }
/// <summary> /// rename registry value [depricated] /// </summary> /// <param name="parent"></param> /// <param name="oldName"></param> /// <param name="newName"></param> static void RenameVal(RegistryKey parent, string oldName, string newName) { try { object val = parent.GetValue(oldName); RegistryValueKind kind = parent.GetValueKind(oldName); parent.SetValue(newName, val, kind); parent.DeleteValue(oldName); } catch { } }
/// <summary>Retrieves the data from the <paramref name="valueName"/> in <paramref name="key"/>.</summary> /// <param name="key">The registry key to get value data.</param> /// <param name="valueName">The name of the value</param> /// <returns>The value data as string, with type prefix if needed.</returns> /// <remarks>The format of the data is <Value type>:<Value data> /// Registry types not in <see cref="RegistryValueKind"/>, could be read using entry in <c>advapi32.dll</c>. /// <para> /// References: /// <ul> /// <li><see href="http://en.wikipedia.org/wiki/Windows_Registry#.REG_files">.REG files (also known as Registration entries)</see></li> /// <li><see href="http://en.wikipedia.org/wiki/Windows_Registry#cite_ref-4">List of standard registry value types</see></li> /// <li><see href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms724884%28v=vs.85%29.aspx">Registry Value Types</see></li> /// <li><see href="http://msdn.microsoft.com/en-us/library/microsoft.win32.registryvaluekind.aspx">RegistryValueKind Enumeration</see></li> /// <li><see href="http://www.dotnetframework.org/default.aspx/Dotnetfx_Vista_SP2/Dotnetfx_Vista_SP2/8@0@50727@4016/DEVDIV/depot/DevDiv/releases/whidbey/NetFxQFE/ndp/clr/src/BCL/Microsoft/Win32/RegistryKey@cs/1/RegistryKey@cs">RegistryKey.cs source code in C# .NET</see></li> /// </ul> /// </para><para> /// <table> /// <caption>Numeric values for Registry Predefined Value Types in <c>Winnt.h</c>.</caption> /// <tr><th>Type</th><th>Value</th></tr> /// <tr><td>REG_NONE</td><td>0</td></tr> /// <tr><td>REG_SZ</td><td>1</td></tr> /// <tr><td>REG_EXPAND_SZ</td><td>2</td></tr> /// <tr><td>REG_BINARY</td><td>3</td></tr> /// <tr><td>REG_DWORD</td><td>4</td></tr> /// <tr><td>REG_DWORD_LITTLE_ENDIAN</td><td>4</td></tr> /// <tr><td>REG_DWORD_BIG_ENDIAN</td><td>5</td></tr> /// <tr><td>REG_LINK</td><td>6</td></tr> /// <tr><td>REG_MULTI_SZ</td><td>7</td></tr> /// <tr><td>REG_RESOURCE_LIST</td><td>8</td></tr> /// <tr><td>REG_FULL_RESOURCE_DESCRIPTOR</td><td>9</td></tr> /// <tr><td>REG_RESOURCE_REQUIREMENTS_LIST</td><td>10</td></tr> /// <tr><td>REG_QWORD</td><td>11</td></tr> /// <tr><td>REG_QWORD_LITTLE_ENDIAN</td><td>11</td></tr> /// </table> /// </para><para> /// <table> /// <caption>Numeric values for Registry Types in <see cref="RegistryValueKind"/> Enumeration.</caption> /// <tr><th>Type</th><th>Value</th></tr> /// <tr><td>None</td><td>-1</td></tr> /// <tr><td>Unknown</td><td>0</td></tr> /// <tr><td>String</td><td>1</td></tr> /// <tr><td>ExpandString</td><td>2</td></tr> /// <tr><td>Binary</td><td>3</td></tr> /// <tr><td>DWord</td><td>4</td></tr> /// <tr><td>MultiString</td><td>7</td></tr> /// <tr><td>QWord</td><td>11</td></tr> /// </table> /// </para> /// </remarks> private static string FormatValueData(RegistryKey key, string valueName) { Contract.Requires(key != null); Contract.Requires(valueName != null); Contract.Ensures(Contract.Result<string>() != null); string text = string.Empty; RegistryValueKind rvk = key.GetValueKind(valueName); object keyValue = key.GetValue(valueName); if (keyValue != null) { switch (rvk) { case RegistryValueKind.None: byte[] none = (byte[])keyValue; text = string.Format(CultureInfo.InvariantCulture, "hex(0):{0}", ByteToHexList(none)); break; case RegistryValueKind.Unknown: throw new UnauthorizedAccessException("Unknown registry value kind."); case RegistryValueKind.String: string value = (string)keyValue; text = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", value.ToString().Replace(@"\", @"\\").Replace(@"""", @"\""")); break; case RegistryValueKind.ExpandString: string expand = (string)keyValue; text = string.Format(CultureInfo.InvariantCulture, "hex(2):{0}", StringToHexList(expand)); break; case RegistryValueKind.Binary: byte[] binary = (byte[])keyValue; text = string.Format(CultureInfo.InvariantCulture, "hex:{0}", ByteToHexList(binary)); break; case RegistryValueKind.DWord: int dword = (int)keyValue; text = string.Format(CultureInfo.InvariantCulture, "dword:{0:x8}", dword); break; case RegistryValueKind.MultiString: string[] multi = (string[])keyValue; text = string.Format(CultureInfo.InvariantCulture, "hex(7):{0}", StringArrayToHexList(multi)); break; case RegistryValueKind.QWord: byte[] qword = (byte[])keyValue; text = string.Format(CultureInfo.InvariantCulture, "hex(b):{0}", ByteToHexList(qword)); break; default: throw new UnauthorizedAccessException("Default registry value kind."); } } return text; }
private void BlueprintRegKeysRecurse(XmlWriter xmlOut, RegistryKey regKey, string curKeyName, string curKeyPortion) { if (!string.IsNullOrEmpty(curKeyPortion)) { xmlOut.WriteStartElement("Key"); xmlOut.WriteAttributeString("path", curKeyPortion); } // Save values foreach (var value in regKey.GetValueNames()) { var type = regKey.GetValueKind(value); xmlOut.WriteStartElement("Value"); xmlOut.WriteAttributeString("name", value); switch (type) { case RegistryValueKind.String: string str = (string)regKey.GetValue(value); try { if (!string.IsNullOrEmpty(str)) XmlConvert.VerifyName(str); xmlOut.WriteAttributeString("string", str); } catch (XmlException) { byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(str); xmlOut.WriteAttributeString("str-base64", Utils.HexDump(bytes)); } break; case RegistryValueKind.DWord: xmlOut.WriteAttributeString("dword", ((Int32)regKey.GetValue(value)).ToString("X")); break; case RegistryValueKind.Binary: byte[] bin = (byte[])regKey.GetValue(value); xmlOut.WriteAttributeString("bin", Utils.HexDump(bin)); break; } xmlOut.WriteEndElement(); } // Recurse on subkeys foreach (var key in regKey.GetSubKeyNames()) { RegistryKey subRegKey = regKey.OpenSubKey(key); BlueprintRegKeysRecurse(xmlOut, subRegKey, Path.Combine(curKeyName, key), key); } if (!string.IsNullOrEmpty(curKeyPortion)) xmlOut.WriteEndElement(); }
public static LWRegistryValueKind Win32RegKeyValueKind(RegistryKey hKey, string sValue) { try { RegistryValueKind valueKind = hKey.GetValueKind(sValue); switch (valueKind) { case RegistryValueKind.Binary: return LWRegistryValueKind.REG_BINARY; case RegistryValueKind.String: return LWRegistryValueKind.REG_SZ; case RegistryValueKind.DWord: return LWRegistryValueKind.REG_DWORD; case RegistryValueKind.ExpandString: return LWRegistryValueKind.REG_EXPAND_SZ; case RegistryValueKind.Unknown: return LWRegistryValueKind.REG_RESOURCE_LIST; case RegistryValueKind.MultiString: return LWRegistryValueKind.REG_MULTI_SZ; case RegistryValueKind.QWord: return LWRegistryValueKind.REG_QUADWORD; default: return LWRegistryValueKind.REG_BINARY; } } catch (Exception ex) { Logger.LogException("Win32RegKeyValueKind : ", ex); return LWRegistryValueKind.REG_SZ; } }
/// <summary> /// Recursively copies a registry key. /// </summary> /// <param name="sourceKey">The source key.</param> /// <param name="destinationKey">The destination key.</param> private static void recursiveCopyKey(RegistryKey sourceKey, RegistryKey destinationKey) { //copy all the values foreach (var valueName in sourceKey.GetValueNames()) { var objValue = sourceKey.GetValue(valueName); var valKind = sourceKey.GetValueKind(valueName); destinationKey.SetValue(valueName, objValue, valKind); } //For Each subKey create a new subKey in destinationKey (recursive) foreach (var sourceSubKeyName in sourceKey.GetSubKeyNames()) { using (var sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName)) { using (var destSubKey = destinationKey.CreateSubKey(sourceSubKeyName)) { recursiveCopyKey(sourceSubKey, destSubKey); } } } }
public RegValue(RegistryKey parentKey, String valueName) : this(valueName, parentKey.GetValueKind(valueName), parentKey.GetValue(valueName)) { ParentKey = parentKey; }
private static void CopyKey(RegistryKey keySource, RegistryKey keyDest) { if (keySource.SubKeyCount > 0) { string[] subkeys = keySource.GetSubKeyNames(); for (int n = 0; n < subkeys.Length; n++) { using (RegistryKey subkeysource = keySource.OpenSubKey(subkeys[n])) { using (RegistryKey subkeydest = keyDest.CreateSubKey(subkeys[n], RegistryKeyPermissionCheck.ReadWriteSubTree)) { CopyKey(subkeysource, subkeydest); } } } } string[] values = keySource.GetValueNames(); for (int n = 0; n < values.Length; n++) { keyDest.SetValue(values[n], keySource.GetValue(values[n]), keySource.GetValueKind(values[n])); } }
public RegistryValueKind GetValueKind(string valueName) { return(registryKey.GetValueKind(valueName)); }
void writeRegKeyValues(StreamWriter sw, int rootKeyLen, RegistryKey key) { //string keyname = key.Name; string keyname = ""; if (rootKeyLen > key.Name.Length) return;//should only happen for the vos root HKCU\..TempVirtReg\myApp\registry keyname = key.Name.Substring(rootKeyLen); if (String.IsNullOrEmpty(keyname)) return; bool found = false; string keynameCheck = keyname + '\\'; foreach (KeyValuePair<String,String> rs in virtualKeys) { if (keynameCheck.StartsWith(rs.Value, StringComparison.InvariantCultureIgnoreCase)) { keyname = keyname.Substring(rs.Value.Length).Insert(0, rs.Key); found = true; break; } } if (!found) { MessageBox.Show(String.Format("Not yet implemented registry key: {0}", keyname)); return; } sw.WriteLine("[{0}]", keyname); foreach (string valuename in key.GetValueNames()) { object value = null; String regvalue = null; RegistryValueKind kind = key.GetValueKind(valuename); string regvaluename = valuename.Replace("\\", "\\\\"); regvaluename = regvaluename.Replace("\"", "\\\""); if (regvaluename.Length == 0) regvaluename = "@"; else regvaluename = "\"" + regvaluename + "\""; if (kind != RegistryValueKind.Unknown) { value = key.GetValue(valuename); } switch (kind) { case RegistryValueKind.Binary: System.Byte[] x = (System.Byte[])value; regvalue = RegFileHelper.ByteArrayToHexComma(x); RegFile.ByteArrayFormatString(ref regvalue, regvaluename.Length + 5); regvalue = "hex:" + regvalue; break; case RegistryValueKind.DWord: regvalue = string.Format("dword:{0:x8}", value); break; case RegistryValueKind.ExpandString: byte[] bytes = Encoding.Unicode.GetBytes((String)value); regvalue = RegFileHelper.ByteArrayToHexComma(bytes); regvalue += (regvalue != "" ? "," : "") + "00,00"; RegFile.ByteArrayFormatString(ref regvalue, regvaluename.Length + 8); regvalue = "hex(2):" + regvalue; break; case RegistryValueKind.MultiString: string[] sa = (string[])value; regvalue = ""; for (int m = 0; m < sa.Length; m++) { bytes = Encoding.Unicode.GetBytes((String)sa[m]); regvalue += RegFileHelper.ByteArrayToHexComma(bytes); regvalue = regvalue + ",00,00,"; } regvalue = regvalue + "00,00"; RegFile.ByteArrayFormatString(ref regvalue, regvaluename.Length + 8); regvalue = "hex(7):" + regvalue; break; case RegistryValueKind.QWord: { long l = (long)value; bytes = System.BitConverter.GetBytes(l); regvalue += RegFileHelper.ByteArrayToHexComma(bytes); regvalue = "hex(b):" + regvalue; break; } case RegistryValueKind.String: regvalue = ((string)value).Replace("\\", "\\\\"); regvalue = regvalue.Replace("\"", "\\\""); regvalue = string.Format("\"{0}\"", regvalue); break; case RegistryValueKind.Unknown: regvalue = "hex(0):"; break; default: errors.Append(String.Format("\r\nWARNING: RegistryFunctions.enumRegKeyValues RegistryValueKind.{0} not supported", kind)); break; } sw.WriteLine("{0}={1}", regvaluename, regvalue); } sw.WriteLine(""); }
/* ----------------------------------------------------------------- */ /// /// LoadValues /// /// <summary> /// レジストリからデータをロードする.レジストリは,階層構造を /// 持つ場合,Subkeys と Values に分かれるため,Values の部分 /// のみを処理する. /// </summary> /// /* ----------------------------------------------------------------- */ private void LoadValues(RegistryKey root, ParameterCollection dest) { foreach (string name in root.GetValueNames()) { if (dest.Contains(name)) continue; var item = new ParameterElement(); item.Key = name; var kind = root.GetValueKind(name); if (kind == Microsoft.Win32.RegistryValueKind.String) { item.Type = ParameterType.String; item.Value = root.GetValue(name, ""); } else if (kind == Microsoft.Win32.RegistryValueKind.DWord) { item.Type = ParameterType.Integer; item.Value = root.GetValue(name, 0); } else { throw new NotSupportedException(kind.ToString()); } dest.Add(item); } }
private void verifyRegConfig(RegistryKey rk) { if (rk.GetValue("maxIndex") == null || rk.GetValueKind("maxIndex") != RegistryValueKind.DWord) rk.SetValue("maxIndex", 5); if (rk.GetValue("ignClass") == null || rk.GetValueKind("ignClass") != RegistryValueKind.MultiString) rk.SetValue("ignClass", new String[] { "tooltips_class32", "Shell_TrayWnd", "NotifyIconOverflowWindow", "Desktop User Picture", "DV2ControlHost", "Progman", "WorkerW", "Alternate Owner", "Internet Explorer_Hidden", "Button", "SysShadow" }, RegistryValueKind.MultiString); if (rk.GetValue("ignProcess") == null || rk.GetValueKind("ignProcess") != RegistryValueKind.MultiString) rk.SetValue("ignProcess", new String[] { "BasicWindow" }, RegistryValueKind.MultiString); }
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; } }
/// <summary> /// Writes specified value to the registry. /// </summary> /// <param name="key">The key.</param> /// <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 RegistryKey Write(RegistryKey key, string path, string valueName, object value) { RegistryKey lastKey = key; string[] parts = path.Split('\\'); if (parts == null || parts.Length == 0) { return null; } 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) { if (valueName == null) { } 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(); return key; }
private static void RecurseCopyKey(RegistryKey sourceKey, RegistryKey destinationKey) { foreach (string valueName in sourceKey.GetValueNames()) { object objValue = sourceKey.GetValue(valueName); RegistryValueKind valKind = sourceKey.GetValueKind(valueName); destinationKey.SetValue(valueName, objValue, valKind); } foreach (string sourceSubKeyName in sourceKey.GetSubKeyNames()) { RegistryKey sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName); RegistryKey destSubKey = destinationKey.CreateSubKey(sourceSubKeyName); RecurseCopyKey(sourceSubKey, destSubKey); } }
static string GetStringValueFromRegistry(RegistryKey key, string valueName) { object val = key.GetValue(valueName); if (val == null) return string.Empty; RegistryValueKind kind = key.GetValueKind(valueName); if (kind == RegistryValueKind.DWord || kind == RegistryValueKind.QWord || kind == RegistryValueKind.String) { return val.ToString(); } else if (kind == RegistryValueKind.ExpandString) { return Environment.ExpandEnvironmentVariables(val as string); } else if (kind == RegistryValueKind.MultiString) { StringBuilder buf = new StringBuilder(); foreach (var s in val as string[]) { buf.AppendFormat("{0}, ", s); } return buf.ToString(); } else if (kind == RegistryValueKind.Binary) { StringBuilder buf = new StringBuilder(); foreach (var b in val as byte[]) { buf.AppendFormat("{0:x2} ", b); } if (buf.Length > 0) buf.Remove(buf.Length - 1, 1); return buf.ToString(); } else return string.Empty; }
private void UpdateList(RegistryKey rKey) { this.lvRegistry.Items.Clear(); string[] names = rKey.GetValueNames(); foreach (string name in names) { ListViewItem lvi = new ListViewItem(name); RegistryValueKind rType = rKey.GetValueKind(name); lvi.Tag = rType; string value = null; if (rType == RegistryValueKind.Binary) { byte[] valueObj = rKey.GetValue(name) as byte[]; foreach (byte item in valueObj) { value += item.ToString("X2") + " "; } } else { value = rKey.GetValue(name).ToString(); } string type = rType.ToString(); lvi.SubItems.Add(type); lvi.SubItems.Add(value.Trim()); this.lvRegistry.Items.Add(lvi); } for (int i = 0; i < this.lvRegistry.Columns.Count; i++) { if (this.lvRegistry.Items.Count > 0) { this.lvRegistry.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); } else { this.lvRegistry.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize); } } }
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 static RegistryValueKind GetValueKind( RegistryKey key, string keyName ) { RegistryValueKind valueKind = RegistryValueKind.Unknown; if ( key.GetValueNames().Contains( keyName ) ) { valueKind = key.GetValueKind( keyName ); } if ( valueKind == RegistryValueKind.Unknown ) { valueKind = RegistryValueKind.String; } return valueKind; }
private static string GetRegistryKeyValue(RegistryKey subkey, string value) { var v = subkey.GetValue(value); if (v == null) { return null; } RegistryValueKind valueKind = subkey.GetValueKind(value); if (valueKind == RegistryValueKind.Binary && v is byte[]) { byte[] valueBytes = (byte[])v; StringBuilder bytes = new StringBuilder(valueBytes.Length * 2); foreach (byte b in valueBytes) { bytes.Append(b.ToString(CultureInfo.InvariantCulture)); bytes.Append(','); } return bytes.ToString(0, bytes.Length - 1); } if (valueKind == RegistryValueKind.MultiString && v is string[]) { var itemList = new StringBuilder(); foreach (string item in (string[])v) { itemList.Append(item); itemList.Append(','); } return itemList.ToString(0, itemList.Length - 1); } return v.ToString(); }
private void FillGrid(string[] str, RegistryKey rg) { DataRow dataRow = null; for (int i = 0; i < str.Length; i++) { dataRow = dataTable.NewRow(); dataRow[0] = str[i]; string valueKind = string.Format("{0}", rg.GetValueKind(str[i])); dataRow[1] = valueKind; string kegistryKeyValue = string.Empty; switch (valueKind) { case "String": case "MultiString": case "DWord": { kegistryKeyValue = rg.GetValue(str[i]).ToString(); } break; case "Binary": { byte[] bytes = (byte[])rg.GetValue(str[i]); kegistryKeyValue = BitConverter.ToString(bytes); } break; } dataRow[2] = kegistryKeyValue; dataTable.Rows.Add(dataRow); } dataGridView1.DataSource = dataTable; }
/// <summary> /// Recursively makes a snapshot of a key and its subkeys. /// </summary> /// <param name="currentKey">The key to snapshot next</param> /// <param name="view">The view currently used (Win64 or Win32)</param> /// <param name="results">The result object to fill out</param> private static void DoRegistrySnapshotKey(RegistryKey currentKey, RegistryView view, LinkedList<SnapshotRegistryItem> results) { // Values string[] valueKeys = currentKey.GetValueNames(); foreach (string key in valueKeys) { SnapshotRegistryValue item = new SnapshotRegistryValue(); item.FullPath = RemoveHive(currentKey.Name + "\\" + key); item.RegistryView = view; try { item.RegistryKeyType = currentKey.GetValueKind(key); item.Value = ValueToString(item.RegistryKeyType, currentKey.GetValue(key)); item.WasReadable = true; } catch (Exception) { item.WasReadable = false; } results.AddLast(item); } // Subkeys string[] subKeys = currentKey.GetSubKeyNames(); foreach (string subKey in subKeys) { SnapshotRegistryKey item = new SnapshotRegistryKey(); item.FullPath = RemoveHive(currentKey.Name + "\\" + subKey); item.RegistryView = view; item.WasReadable = false; try { using (RegistryKey sub = currentKey.OpenSubKey(subKey)) { try { DoRegistrySnapshotKey(sub, view, results); } catch (Exception) { // Set item.WasReadable without taking subkeys exceptions into account } } item.WasReadable = true; } catch (Exception) { item.WasReadable = false; } results.AddLast(item); } }