LicenseSourceResult ReadFromRegistry(RegistryView view, string applicationName) { try { using (var rootKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view)) using (var registryKey = rootKey.OpenSubKey(keyPath)) { if (registryKey == null) { return ValidateLicense(null, applicationName); } var regValue = registryKey.GetValue("License", null); var licenseText = (regValue is string[]) ? string.Join(" ", (string[])regValue) : (string)regValue; return ValidateLicense(licenseText, applicationName); } } catch (SecurityException) { return new LicenseSourceResult { Location = location, Result = $"Insufficent rights to read license from {location}" }; } }
static bool RegistryKeyExists(string keyName, RegistryView registryView) { var localKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView); localKey = localKey.OpenSubKey(keyName); return localKey != null; }
public static object ReadKey(RegistryHive hive, RegistryView view, string subkey, string name) { // open root RegistryKey rootKey = Microsoft.Win32.RegistryKey.OpenBaseKey(hive, view); if (rootKey == null) { return null; } // look for key RegistryKey key = rootKey.OpenSubKey(subkey); if (key == null) { return null; } // look for value object value = key.GetValue(name); if (value == null) { return null; } return value; }
/// <summary> /// Given a registry path, locate the correct root key and return the relative path. For example, when the user gives the absolute registry path /// /// HKEY_LOCAL_MACHINE\Software\Microsoft /// /// you really have two parts: HKEY_LOCAL_MACHINE is a "registry hive" root, and "Software\Microsoft" the relative path. /// </summary> /// <param name="rootPath">absolute registry path</param> /// <param name="rootPathWithoutHive">Returns the relative path</param> /// <param name="registryView">Type of registry you want to see (32-bit, 64-bit, default).</param> /// <param name="remoteMachineName">Name of a remote machine. User must ensure that caller has sufficient privileges to access the key</param> /// <returns>"registry hive" root</returns> public static RegistryKey OpenRegistryHive(string rootPath, out string rootPathWithoutHive, RegistryView registryView, string remoteMachineName = null) { rootPathWithoutHive = ""; bool found = false; foreach (string key in KnownHives.Keys) { if (rootPath.StartsWith(key+"\\", StringComparison.OrdinalIgnoreCase)) { rootPathWithoutHive = rootPath.Substring(key.Length+1); found = true; } if (rootPath.Equals(key, StringComparison.OrdinalIgnoreCase)) { rootPathWithoutHive = rootPath.Substring(key.Length); found = true; } if (found) { if (string.IsNullOrEmpty(remoteMachineName)) { return RegistryKey.OpenBaseKey(KnownHives[key], registryView); } else { return RegistryKey.OpenRemoteBaseKey(KnownHives[key], remoteMachineName, registryView); } } } Trace.TraceWarning("'{0}' is not a well-formed registry path", rootPath); return null; }
public static void Init(RegistryView settingsRoot, IDictionary<string, IEnumerable<string>> options) { if (BitlySettings == null) { BitlySettings = settingsRoot["bitly"]; bitlyUsername = BitlySettings["#username"].StringValue; bitlySecret = BitlySettings["#password"].EncryptedStringValue; foreach (var arg in options.Keys) { var argumentParameters = options[arg]; var last = argumentParameters.LastOrDefault(); switch (arg) { case "bitly-username": bitlyUsername = last; BitlySettings["#username"].StringValue = bitlyUsername; break; case "bitly-secret": bitlySecret = last; BitlySettings["#password"].EncryptedStringValue = bitlySecret; break; } } } }
public RegistrySettingsProvider (RegistryHive hKey, RegistryView view = RegistryView.Default, string baseKey = null) { this.hKey = hKey; this.view = view; this.baseKey = baseKey ?? ProductInfo.Company + "\\" + ProductInfo.Product; }
public IRegistryKey FromHandle( SafeRegistryHandle handle, RegistryView view ) { return new RegistryKeyWrap(RegistryKey.FromHandle(handle, view)); }
private void add_key(IList<RegistryKey> keys, RegistryHive hive, RegistryView view) { FaultTolerance.try_catch_with_logging_exception( () => keys.Add(RegistryKey.OpenBaseKey(hive, view)), "Could not open registry hive '{0}' for view '{1}'".format_with(hive.to_string(), view.to_string()), logWarningInsteadOfError: true); }
string ReadLicenseFromRegistry(RegistryView view) { try { using (var rootKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, view)) using (var registryKey = rootKey.OpenSubKey(keyPath)) { if (registryKey == null) { return null; } var licenseValue = registryKey.GetValue("License", null); if (licenseValue is string[]) { return string.Join(" ", (string[])licenseValue); } return (string)licenseValue; } } catch { return null; } }
public IRegistryKey OpenBaseKey( RegistryHive hKey, RegistryView view ) { return new RegistryKeyWrap(RegistryKey.OpenBaseKey(hKey, view)); }
public IRegistryKey OpenRemoteBaseKey( RegistryHive hKey, string machineName, RegistryView view ) { return new RegistryKeyWrap(RegistryKey.OpenRemoteBaseKey(hKey, machineName, view)); }
static void DeleteKey(RegistryHive hive, RegistryView view, string guid) { using (RegistryKey key = RegistryKey.OpenBaseKey(hive, view)) { key.DeleteSubKey("Software\\Classes\\CLSID\\" + guid + "\\ProgId", false); key.DeleteSubKey("Software\\Classes\\CLSID\\" + guid + "\\InProcServer32", false); key.DeleteSubKey("Software\\Classes\\CLSID\\" + guid, false); } }
private PermissionPolicy( string name, string description, IEnumerable<WellKnownSidType> defaults ) { Name = name; Description = description; _defaults = defaults; policyView = _policies["#" + Name]; Refresh(); AllPolicies = AllPolicies.UnionSingleItem(this).ToArray(); }
private static string FindRegistryValueUnderKey(string registryBaseKeyName, string registryKeyName, RegistryView registryView) { using (RegistryKey registryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView)) { using (RegistryKey registryKey2 = registryKey.OpenSubKey(registryBaseKeyName)) { return registryKey2?.GetValue(registryKeyName)?.ToString() ?? string.Empty; } } }
public void RegisterTypeLib(System.Reflection.Assembly typeLib, RegistryView registryView ) { var reg = ComClrInfoFactory.CreateTypeLib(typeLib); #if NET35 throw new NotImplementedException("Need to backport 4.0 methods"); #else var root = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, registryView); var classes = root.CreateSubKey(CLASSES); registerTypeLib(classes, reg); #endif }
/// <summary> /// The default constructor takes a registry root path encoded as a string (for example, HKEY_LOCAL_MACHINE\Software\Microsoft) /// and reads everything under it. /// </summary> /// <param name="rootPath">Root path</param> /// <param name="registryView">Type of registry you want to see (32-bit, 64-bit, default).</param> public RegistryImporter(string rootPath, RegistryView registryView) { Result = new RegKeyEntry(null, rootPath); string rootPathWithoutHive; RegistryKey rootKey = Regis3.OpenRegistryHive(rootPath, out rootPathWithoutHive, registryView); using (RegistryKey key = rootKey.OpenSubKey(rootPathWithoutHive)) { ImportRecursive(Result, key); } }
public void UnregisterInProcServer(Type t, RegistryView registryView = RegistryView.Default) { var reg = ComClrInfoFactory.CreateClass(t); #if NET35 throw new NotImplementedException("Need to backport 4.0 methods"); #else var root = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView); var classes = root.CreateSubKey(CLASSES); unregisterInProcServer(classes, reg); #endif }
static void CreateKeys(RegistryHive hive, RegistryView view, string guid, string libraryId, string classId, string path) { using (RegistryKey key = RegistryKey.OpenBaseKey(hive, view)) { using (RegistryKey subKey = key.CreateSubKey("Software\\Classes\\CLSID\\" + guid)) subKey.SetValue(null, classId + " Class"); using (RegistryKey subKey = key.CreateSubKey("Software\\Classes\\CLSID\\" + guid + "\\InProcServer32")) subKey.SetValue(null, path); using (RegistryKey subKey = key.CreateSubKey("Software\\Classes\\CLSID\\" + guid + "\\ProgId")) subKey.SetValue(null, libraryId + "." + classId); } }
public void UnregisterInterface(Type type, RegistryView registryView = RegistryView.Default) { var reg = ComClrInfoFactory.CreateInterface(type); #if NET35 throw new NotImplementedException("Need to backport 4.0 methods"); #else var root = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, registryView); var classes = root.CreateSubKey(CLASSES); unregisterInterface(classes, reg); #endif }
static string ReadRegistry(RegistryView view, string keyName, string defaultValue) { using (var key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view).OpenSubKey(@"SOFTWARE\ParticularSoftware\ServiceBus")) { if (key == null) { return defaultValue; } return (string) key.GetValue(keyName, defaultValue); } }
/// <summary> /// This constructor creates a registry importer for an existing registry key /// </summary> /// <param name="existingRegistry">Existing registry key</param> /// <param name="registryView">Type of registry you want to see (32-bit, 64-bit, default).</param> public RegistryImportRelativeToExistingRegKeyEntry(RegKeyEntry existingRegistry, RegistryView registryView) { Result = new RegKeyEntry(null, existingRegistry.Path); string rootPath = existingRegistry.Path; string rootPathWithoutHive; RegistryKey rootKey = Regis3.OpenRegistryHive(rootPath, out rootPathWithoutHive, registryView); using (RegistryKey key = rootKey.OpenSubKey(rootPathWithoutHive)) { ImportRecursive(Result, key, existingRegistry); } }
private ODBC GetDataAndConstructOdbcObject(RegistryHive hiveToUse, RegistryView viewToUse, string stringToReplace, string path, string odbcKey) { RegistryKey odbcReg = RegistryKey.OpenBaseKey(hiveToUse, viewToUse); odbcReg = odbcReg.OpenSubKey(path); odbcReg = odbcReg.OpenSubKey(odbcKey); string server = (string)odbcReg.GetValue("server"); string driver = (string)odbcReg.GetValue("driver"); string name = odbcReg.Name.Replace(stringToReplace + "\\" + path + "\\", ""); string dsn = name; ODBC odbcObject = new ODBC(dsn, driver, server); return odbcObject; }
private static string GetRegistryValue(RegistryHive hive, RegistryView view, string path, string name) { using (var baseKey = RegistryKey.OpenBaseKey(hive, view)) using (var node = baseKey.OpenSubKey(path)) { if (node != null) { return (node.GetValue(name) as string) ?? string.Empty; } return string.Empty; } }
public static string[] GetSubKeys(RegistryHive hive, RegistryView view, string key) { RegistryKey rootKey = RegistryKey.OpenBaseKey(hive, view); if (rootKey == null) return null; RegistryKey subkey = rootKey.OpenSubKey(key); if (subkey == null) return null; return subkey.GetSubKeyNames(); }
/// <summary> /// Constructor /// </summary> public AssemblyFoldersExInfo(RegistryHive hive, RegistryView view, string registryKey, string directoryPath, Version targetFrameworkVersion) { ErrorUtilities.VerifyThrowArgumentNull(registryKey, "registryKey"); ErrorUtilities.VerifyThrowArgumentNull(directoryPath, "directoryPath"); ErrorUtilities.VerifyThrowArgumentNull(targetFrameworkVersion, "targetFrameworkVersion"); Hive = hive; View = view; Key = registryKey; DirectoryPath = directoryPath; TargetFrameworkVersion = targetFrameworkVersion; }
public static void Initialize() { if (String.IsNullOrEmpty(mAppRootDir)) //not yet initialized (or maybe HV2 is not installed) { HV2RegInfo regInfo = new HV2RegInfo(); //Populate local members mAppRootDir = regInfo.AppRoot; mDefaultHelpViewerCLSID = regInfo.DefaultHelpViewerCLSID; mContentStore = regInfo.ContentStore; mRegistryView = regInfo.RegistryView; } }
public RegHive Invoke() { if (System.Environment.Is64BitOperatingSystem) { Root = @"SOFTWARE\Wow6432Node\ProFxENGAGEMENT30\WM\"; View = RegistryView.Registry64; } else { Root = @"SOFTWARE\ProFxENGAGEMENT30\WM\"; View = RegistryView.Registry32; } return this; }
static bool Register(RegistryView view, string guid, string libraryId, string classId, string path) { try { CreateKeys(RegistryHive.LocalMachine, view, guid, libraryId, classId, path); } catch (UnauthorizedAccessException) { try { CreateKeys(RegistryHive.CurrentUser, view, guid, libraryId, classId, path); } catch (UnauthorizedAccessException) { return false; } } return true; }
private void StartWatching(RegistryHive hive, RegistryView view) { var tag = RegistryWatcher.Instance.TryAdd( hive, view, PythonCorePath, Registry_PythonCorePath_Changed, recursive: true, notifyValueChange: true, notifyKeyChange: true ) ?? RegistryWatcher.Instance.TryAdd( hive, view, PythonPath, Registry_PythonPath_Changed, recursive: false, notifyValueChange: false, notifyKeyChange: true ) ?? RegistryWatcher.Instance.Add( hive, view, "Software", Registry_Software_Changed, recursive: false, notifyValueChange: false, notifyKeyChange: true ); }
/// <summary> /// Creates a new event object. /// </summary> /// <param name="key">The key that was originally provided.</param> public RegistryChangedEventArgs(RegistryHive hive, RegistryView view, string key, bool isRecursive, bool isValueChange, bool isKeyChange, object tag) { Hive = hive; View = view; Key = key; IsRecursive = isRecursive; IsValueChanged = isValueChange; IsKeyChanged = isKeyChange; Tag = tag; }
public static RegistryKey FromHandle(SafeRegistryHandle handle, RegistryView view) { throw new PlatformNotSupportedException(); }
internal async Task RegScan(RegistryHive RegHive, RegistryView RegView, List <AddSoftware> lScanList) { await Task.Run(() => _RegScan(RegHive, RegView, lScanList)); }
private static object GetValueFromRegistry(RegistryHive registryHive, string key, string valueName, RegistryView view) { RegistryKey localKey = RegistryKey.OpenBaseKey(registryHive, view); RegistryKey localKeySub = localKey.OpenSubKey(key); object value = localKeySub == null ? null : localKeySub.GetValue(valueName); return(value); }
public static object GetRegValue(RegistryView view, string regPath, string ValueName, RegistryHive hive = RegistryHive.LocalMachine) { return(RegistryKey.OpenBaseKey(hive, view) ?.OpenSubKey(regPath)?.GetValue(ValueName)); }
public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineName, RegistryView view) { throw new PlatformNotSupportedException(); }
/// Read registry string. /// This also supports a means to look for high-versioned keys by use /// of a $VERSION placeholder in the key path. /// $VERSION in the key path is a placeholder for the version number, /// causing the highest value path to be searched for and used. /// I.e. "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio". /// There can be additional characters in the component. Only the numeric /// characters are compared. static bool GetToolchainsFromSystemRegistry(string keyPath, string valueName, ICollection <ToolchainVersion> entries, RegistryView view) { string subKey; var hive = GetRegistryHive(keyPath, out subKey); using (var rootKey = RegistryKey.OpenBaseKey(hive, view)) using (var key = rootKey.OpenSubKey(subKey, writable: false)) { if (key == null) { return(false); } foreach (var subKeyName in key.GetSubKeyNames()) { ToolchainVersion entry; if (HandleToolchainRegistrySubKey(out entry, key, valueName, subKeyName)) { entries.Add(entry); } } } return(true); }
private static void OperateReg(RegistryHive hive, string path, Dictionary <string, string[]> parameters, RegistryView view) { SafeRegistryHandle handle = new SafeRegistryHandle(GetHiveHandle(hive), true); RegistryKey r = RegistryKey.FromHandle(handle, view).CreateSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree); //一般情况是使用如下代码: //RegistryKey rk = Registry.LocalMachine.CreateSubKey(path); if (parameters == null && parameters.Count <= 0) { return; } List <string> keys = parameters.Keys.ToList(); for (int i = 0; i < parameters.Count; i++) { //string to RegistryValueKind RegistryValueKind rv = (RegistryValueKind)Enum.Parse(typeof(RegistryValueKind), parameters[keys[i]][1].ToString(), true); r.SetValue(keys[i], parameters[keys[i]][0], rv); LogHelper.WriteWarn("修改注册表成功"); } }
/// Read registry strings looking for matching values. public static bool GetToolchainsFromSystemRegistryValues(string keyPath, string matchValue, ICollection <ToolchainVersion> entries, RegistryView view) { string subKey; var hive = GetRegistryHive(keyPath, out subKey); using (var rootKey = RegistryKey.OpenBaseKey(hive, view)) using (var key = rootKey.OpenSubKey(subKey, writable: false)) { if (key == null) { return(false); } foreach (var valueName in key.GetValueNames()) { if (!valueName.Contains(matchValue)) { continue; } var value = key.GetValue(valueName) as string; if (value == null) { continue; } float version = 0; // Get the number version from the key value. var match = Regex.Match(value, @".*([1-9][0-9]*\.?[0-9]*)"); if (match.Success) { float.TryParse(match.Groups[1].Value, NumberStyles.Number, CultureInfo.InvariantCulture, out version); } var entry = new ToolchainVersion { Directory = value, Version = version, Value = valueName }; entries.Add(entry); } } return(true); }
static string GetUserOrLmPathInternal(string regKey, string regVal, RegistryView view) => GetNullIfPathEmpty(Tools.Generic.NullSafeGetRegKeyValue <string>(regKey, regVal, view, RegistryHive.CurrentUser)) ?? GetNullIfPathEmpty(Tools.Generic.NullSafeGetRegKeyValue <string>(regKey, regVal, view));
protected static RegistryKey OpenSubKey(RegistryHive hive, string subKey, RegistryView view) { var baseKey = RegistryKey.OpenBaseKey(hive, view); return(baseKey.OpenSubKey(subKey)); }
public bool getSeverConnection() { ////Start service when it was not running ManagedComputer managerCmp = new ManagedComputer(); /* * // Service service = default(Service); * foreach (Service service in managerCmp.Services) * { * if (service.ServiceState != ServiceState.Running) * { * if (service.ServiceState == ServiceState.Paused) * { * service.Resume(); * } * else * { * service.Start(); * } * service.Refresh(); * } * * }*/ //Get Instance of Sqlsever RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32; using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView)) { RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false); if (instanceKey != null) { foreach (var instanceName in instanceKey.GetValueNames()) { //if (instanceName.ToLower() == "SQLEXPRESS".ToLower()) //{ // object temp = Environment.MachineName + @"\" + instanceName; // cmbServerName.Properties.Items.Add(temp); //} //else //{ object temp = Environment.MachineName; cmbServerName.Properties.Items.Add(temp); //} } return(true); } else { XtraMessageBox.Show("Microsoft SQL server chưa được cài đặt trên máy của bạn!\nXin vui cài đặt và thử lại!"); return(false); } //else //{ // foreach (ServerInstance sever in managerCmp.ServerInstances) // { // object temp = managerCmp.Name + @"\" + sever.Name; // cmbServerName.Properties.Items.Add(temp); // } // return true; //} } }
/// <summary> /// Given a registry path, locate the correct root key and return the relative path. For example, when the user gives the absolute registry path /// /// HKEY_LOCAL_MACHINE\Software\Microsoft /// /// you really have two parts: HKEY_LOCAL_MACHINE is a "registry hive" root, and "Software\Microsoft" the relative path. /// </summary> /// <param name="rootPath">absolute registry path</param> /// <param name="rootPathWithoutHive">Returns the relative path</param> /// <param name="registryView">Type of registry you want to see (32-bit, 64-bit, default).</param> /// <param name="remoteMachineName">Name of a remote machine. User must ensure that caller has sufficient privileges to access the key</param> /// <returns>"registry hive" root</returns> public static RegistryKey OpenRegistryHive(string rootPath, out string rootPathWithoutHive, RegistryView registryView, string remoteMachineName = null) { rootPathWithoutHive = ""; bool found = false; foreach (string key in KnownHives.Keys) { if (rootPath.StartsWith(key + "\\", StringComparison.OrdinalIgnoreCase)) { rootPathWithoutHive = rootPath.Substring(key.Length + 1); found = true; } if (rootPath.Equals(key, StringComparison.OrdinalIgnoreCase)) { rootPathWithoutHive = rootPath.Substring(key.Length); found = true; } if (found) { if (string.IsNullOrEmpty(remoteMachineName)) { return(RegistryKey.OpenBaseKey(KnownHives[key], registryView)); } else { return(RegistryKey.OpenRemoteBaseKey(KnownHives[key], remoteMachineName, registryView)); } } } Trace.TraceWarning("'{0}' is not a well-formed registry path", rootPath); return(null); }
private void FindDirectories(RegistryView view, RegistryHive hive, string registryKeyRoot, string targetRuntimeVersion, string registryKeySuffix, string osVersion, string platform, GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, OpenBaseKey openBaseKey) { RegistryKey baseKey = openBaseKey(hive, view); IEnumerable versions = getRegistrySubKeyNames(baseKey, registryKeyRoot); if (versions != null) { ArrayList list = GatherVersionStrings(targetRuntimeVersion, versions); ArrayList list2 = new ArrayList(); ReverseVersionComparer comparer = ReverseVersionComparer.Comparer; foreach (string str in list) { string subKey = registryKeyRoot + @"\" + str + @"\" + registryKeySuffix; IEnumerable enumerable2 = getRegistrySubKeyNames(baseKey, subKey); ArrayList list3 = new ArrayList(); foreach (string str3 in enumerable2) { list3.Add(str3); } list3.Sort(comparer); foreach (string str4 in list3) { list2.Add(subKey + @"\" + str4); } } ArrayList list4 = new ArrayList(); foreach (string str5 in list2) { IEnumerable enumerable3 = getRegistrySubKeyNames(baseKey, str5); ArrayList c = new ArrayList(); foreach (string str6 in enumerable3) { c.Add(str5 + @"\" + str6); } c.Sort(comparer); list4.AddRange(c); list4.Add(str5); } foreach (string str7 in list4) { if (!string.IsNullOrEmpty(platform) || !string.IsNullOrEmpty(osVersion)) { RegistryKey keyPlatform = baseKey.OpenSubKey(str7, false); if ((keyPlatform != null) && (keyPlatform.ValueCount > 0)) { if ((platform != null) && (platform.Length > 0)) { string str8 = keyPlatform.GetValue("Platform", null) as string; if (!string.IsNullOrEmpty(str8) && !this.MatchingPlatformExists(platform, str8)) { continue; } } if ((osVersion != null) && (osVersion.Length > 0)) { Version v = VersionUtilities.ConvertToVersion(osVersion); if (!this.IsVersionInsideRange(v, keyPlatform)) { continue; } } } } string str9 = getRegistrySubKeyDefaultValue(baseKey, str7); if (str9 != null) { this.directoryNames.Add(str9); } } } }
private void FindUnderRegistryHive(RegistryView view, string registryKeyRoot, string targetRuntimeVersion, string registryKeySuffix, string osVersion, string platform, GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, OpenBaseKey openBaseKey) { this.FindDirectories(view, RegistryHive.CurrentUser, registryKeyRoot, targetRuntimeVersion, registryKeySuffix, osVersion, platform, getRegistrySubKeyNames, getRegistrySubKeyDefaultValue, openBaseKey); this.FindDirectories(view, RegistryHive.LocalMachine, registryKeyRoot, targetRuntimeVersion, registryKeySuffix, osVersion, platform, getRegistrySubKeyNames, getRegistrySubKeyDefaultValue, openBaseKey); }
private static RegistryKey OpenRemoteBaseKeyCore(RegistryHive hKey, string machineName, RegistryView view) { throw new PlatformNotSupportedException(SR.Security_RegistryPermission); // remote stores not supported on Unix }
/// <summary> /// Parse all the Subkeys of the given SearchKey into ComObjects and returns a list of them /// </summary> /// <param name="SearchKey">The Registry Key to search</param> /// <param name="View">The View of the registry to use</param> public static IEnumerable <CollectObject> ParseComObjects(RegistryKey SearchKey, RegistryView View, bool SingleThreaded = false) { if (SearchKey == null) { return(new List <CollectObject>()); } List <ComObject> comObjects = new List <ComObject>(); var fsc = new FileSystemCollector(new CollectCommandOptions() { SingleThread = SingleThreaded }); Action <string> ParseComObjectsIn = SubKeyName => { try { RegistryKey CurrentKey = SearchKey.OpenSubKey(SubKeyName); var RegObj = RegistryWalker.RegistryKeyToRegistryObject(CurrentKey, View); if (RegObj != null) { ComObject comObject = new ComObject(RegObj); foreach (string ComDetails in CurrentKey.GetSubKeyNames()) { if (ComDetails.Contains("InprocServer32")) { var ComKey = CurrentKey.OpenSubKey(ComDetails); var obj = RegistryWalker.RegistryKeyToRegistryObject(ComKey, View); string?BinaryPath32 = null; if (obj != null && obj.Values?.TryGetValue("", out BinaryPath32) is bool successful) { if (successful && BinaryPath32 != null) { // Clean up cases where some extra spaces are thrown into the start (breaks our permission checker) BinaryPath32 = BinaryPath32.Trim(); // Clean up cases where the binary is quoted (also breaks permission checker) if (BinaryPath32.StartsWith("\"") && BinaryPath32.EndsWith("\"")) { BinaryPath32 = BinaryPath32.AsSpan().Slice(1, BinaryPath32.Length - 2).ToString(); } // Unqualified binary name probably comes from Windows\System32 if (!BinaryPath32.Contains("\\") && !BinaryPath32.Contains("%")) { BinaryPath32 = Path.Combine(Environment.SystemDirectory, BinaryPath32.Trim()); } comObject.x86_Binary = fsc.FilePathToFileSystemObject(BinaryPath32.Trim()); } } } if (ComDetails.Contains("InprocServer64")) { var ComKey = CurrentKey.OpenSubKey(ComDetails); var obj = RegistryWalker.RegistryKeyToRegistryObject(ComKey, View); string?BinaryPath64 = null; if (obj != null && obj.Values?.TryGetValue("", out BinaryPath64) is bool successful) { if (successful && BinaryPath64 != null) { // Clean up cases where some extra spaces are thrown into the start (breaks our permission checker) BinaryPath64 = BinaryPath64.Trim(); // Clean up cases where the binary is quoted (also breaks permission checker) if (BinaryPath64.StartsWith("\"") && BinaryPath64.EndsWith("\"")) { BinaryPath64 = BinaryPath64.AsSpan().Slice(1, BinaryPath64.Length - 2).ToString(); } // Unqualified binary name probably comes from Windows\System32 if (!BinaryPath64.Contains("\\") && !BinaryPath64.Contains("%")) { BinaryPath64 = Path.Combine(Environment.SystemDirectory, BinaryPath64.Trim()); } comObject.x64_Binary = fsc.FilePathToFileSystemObject(BinaryPath64.Trim()); } } } } comObjects.Add(comObject); } } catch (Exception e) when( e is System.Security.SecurityException || e is ObjectDisposedException || e is UnauthorizedAccessException || e is IOException) { Log.Debug($"Couldn't parse {SubKeyName}"); } }; try { if (SingleThreaded) { foreach (var subKey in SearchKey.GetSubKeyNames()) { ParseComObjectsIn(subKey); } } else { SearchKey.GetSubKeyNames().AsParallel().ForAll(subKey => ParseComObjectsIn(subKey)); } } catch (Exception e) { Log.Debug("Failing parsing com objects {0} {1}", SearchKey.Name, e.GetType()); } return(comObjects); }
private static RegistryKey OpenBaseKeyCore(RegistryHive hKey, RegistryView view) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); }
private static RegistryKey OpenRemoteBaseKeyCore(RegistryHive hKey, string machineName, RegistryView view) { int index = (int)hKey & 0x0FFFFFFF; if (index < 0 || index >= s_hkeyNames.Length || ((int)hKey & 0xFFFFFFF0) != 0x80000000) { throw new ArgumentException(SR.Arg_RegKeyOutOfRange); } // connect to the specified remote registry int ret = Interop.Advapi32.RegConnectRegistry(machineName, new SafeRegistryHandle(new IntPtr((int)hKey), false), out SafeRegistryHandle foreignHKey); if (ret == Interop.Errors.ERROR_DLL_INIT_FAILED) { // return value indicates an error occurred throw new ArgumentException(SR.Arg_DllInitFailure); } if (ret != 0) { Win32ErrorStatic(ret, null); } if (foreignHKey.IsInvalid) { // return value indicates an error occurred throw new ArgumentException(SR.Format(SR.Arg_RegKeyNoRemoteConnect, machineName)); } RegistryKey key = new RegistryKey(foreignHKey, true, false, true, ((IntPtr)hKey) == HKEY_PERFORMANCE_DATA, view); key._checkMode = RegistryKeyPermissionCheck.Default; key._keyName = s_hkeyNames[index]; return(key); }
/// <summary> /// Given a hive and a hive view open the base key /// RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, view); /// </summary> /// <param name="hive">The hive.</param> /// <param name="view">The hive view</param> /// <returns>A registry Key for the given baseKey and view</returns> internal static RegistryKey OpenBaseKey(RegistryHive hive, RegistryView view) { RegistryKey key = RegistryKey.OpenBaseKey(hive, view); return(key); }
/// <summary> /// Creates a RegistryKey. /// This key is bound to hkey, if writable is <b>false</b> then no write operations /// will be allowed. If systemkey is set then the hkey won't be released /// when the object is GC'ed. /// The remoteKey flag when set to true indicates that we are dealing with registry entries /// on a remote machine and requires the program making these calls to have full trust. /// </summary> private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view) { _hkey = hkey; _keyName = ""; _remoteKey = remoteKey; _regView = view; if (systemkey) { _state |= StateFlags.SystemKey; } if (writable) { _state |= StateFlags.WriteAccess; } if (isPerfData) { _state |= StateFlags.PerfData; } ValidateKeyView(view); }
public IRegistryKey OpenBaseKey(RegistryHive hive, RegistryView view) { return(new RegistryBaseKeyMock(_keys)); }
/// <summary> /// Finds directories for a specific registry key. /// </summary> /// <param name="baseKey">Base to look for directories under.</param> /// <param name="registryKeyRoot">Like Software\Microsoft\[.NetFramework | .NetCompactFramework]</param> /// <param name="targetRuntimeVersion">The runtime version property from the project file.</param> /// <param name="registryKeySuffix">Like [ PocketPC | SmartPhone | WindowsCE]\AssemblyFoldersEx</param> /// <param name="getRegistrySubKeyNames">Used to find registry subkey names.</param> /// <param name="getRegistrySubKeyDefaultValue">Used to find registry key default values.</param> private void FindDirectories ( RegistryView view, RegistryHive hive, string registryKeyRoot, string targetRuntimeVersion, string registryKeySuffix, string osVersion, string platform, GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, OpenBaseKey openBaseKey ) { // Open the hive for a given view using (RegistryKey baseKey = openBaseKey(hive, view)) { IEnumerable <string> versions = getRegistrySubKeyNames(baseKey, registryKeyRoot); // No versions found. if (versions == null) { return; } List <ExtensionFoldersRegistryKey> versionStrings = GatherVersionStrings(targetRuntimeVersion, versions); // Loop the versions, looking for component keys. List <ExtensionFoldersRegistryKey> componentKeys = new List <ExtensionFoldersRegistryKey>(); foreach (ExtensionFoldersRegistryKey versionString in versionStrings) { // Make like SOFTWARE\MICROSOFT\.NetFramework\v2.0.x86chk\AssemblyFoldersEx string fullVersionKey = registryKeyRoot + @"\" + versionString.RegistryKey + @"\" + registryKeySuffix; IEnumerable <string> components = getRegistrySubKeyNames(baseKey, fullVersionKey); if (components != null) { // Sort the components in reverse alphabetical order so values with higher alphabetical names are earlier in the array. // This is to try and get newer versioned components based on the fact they should have higher versioned names. List <string> sortedComponents = new List <string>(); foreach (string component in components) { sortedComponents.Add(component); } // The reason we sort here rather than on the component keys is that we do not want to sort using the FullVersionKey // the versions have already been sorted (with things that look like raw drops being tacked onto the bottom of the list after sorting) // By sorting the versions again we will get these raw drop numbers possibly being somewhere other than at the bottom and thereby cause the resolver // to find the assembly in the wrong location. sortedComponents.Sort(ReverseStringGenericComparer.Comparer); foreach (string component in sortedComponents) { // ComponentKeys are like SOFTWARE\MICROSOFT\.NetFramework\v1.0.x86chk\AssemblyFoldersEx\Infragistics.GridControl.1.0 componentKeys.Add(new ExtensionFoldersRegistryKey(fullVersionKey + @"\" + component, versionString.TargetFrameworkVersion)); } } } // Loop the component keys, looking for servicing keys. List <ExtensionFoldersRegistryKey> directoryKeys = new List <ExtensionFoldersRegistryKey>(); foreach (ExtensionFoldersRegistryKey componentKey in componentKeys) { IEnumerable <string> servicingKeys = getRegistrySubKeyNames(baseKey, componentKey.RegistryKey); if (servicingKeys != null) { List <string> fullServicingKeys = new List <string>(); foreach (string servicingKey in servicingKeys) { // ServicingKeys are like SOFTWARE\MICROSOFT\.NetFramework\v1.0.3705\AssemblyFoldersEx\Infragistics.GridControl.1.0\9120 fullServicingKeys.Add(componentKey.RegistryKey + @"\" + servicingKey); } // Alphabetize to put them in version order. fullServicingKeys.Sort(ReverseStringGenericComparer.Comparer); foreach (string key in fullServicingKeys) { directoryKeys.Add(new ExtensionFoldersRegistryKey(key, componentKey.TargetFrameworkVersion)); } directoryKeys.Add(componentKey); } } // Now, we have a properly ordered collection of registry keys, each of which // should point to a default value with a file path. Get those files paths. foreach (ExtensionFoldersRegistryKey directoryKey in directoryKeys) { if (!(String.IsNullOrEmpty(platform) && String.IsNullOrEmpty(osVersion))) { using (RegistryKey keyPlatform = baseKey.OpenSubKey(directoryKey.RegistryKey, false)) { if (keyPlatform != null && keyPlatform.ValueCount > 0) { if (platform != null && platform.Length > 0) { string platformValue = keyPlatform.GetValue("Platform", null) as string; if (!String.IsNullOrEmpty(platformValue) && !MatchingPlatformExists(platform, platformValue)) { continue; } } if (osVersion != null && osVersion.Length > 0) { Version ver = VersionUtilities.ConvertToVersion(osVersion); if (!IsVersionInsideRange(ver, keyPlatform)) { continue; } } } } } string directoryName = getRegistrySubKeyDefaultValue(baseKey, directoryKey.RegistryKey); if (null != directoryName) { _directoryNames.Add(new AssemblyFoldersExInfo(hive, view, directoryKey.RegistryKey, directoryName, directoryKey.TargetFrameworkVersion)); } } } }
static string GetUserOrLmPath(string regKey, string regVal = "", RegistryView view = RegistryView.Registry32) { var path = GetUserOrLmPathInternal(regKey, regVal, view); return(!Tools.FileUtil.IsValidRootedPath(path) ? null : Tools.FileUtil.CleanPath(path)); }
public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view) { throw new PlatformNotSupportedException(); }
/// <summary> /// Get the value of the registry key from one of the RegistryView's specified /// </summary> internal static object GetRegistryValueFromView(string keyName, string valueName, object defaultValue, ArraySegment <object> views) { // We will take on handing of default value // A we need to act on the null return from the GetValue call below // so we can keep searching other registry views object result = defaultValue; // If we haven't been passed any views, then we'll just use the default view if (views.Count == 0) { views = new ArraySegment <object>(DefaultRegistryViews); } foreach (object viewObject in views) { if (viewObject is string viewAsString) { string typeLeafName = typeof(RegistryView).Name + "."; string typeFullName = typeof(RegistryView).FullName + "."; // We'll allow the user to specify the leaf or full type name on the RegistryView enum viewAsString = viewAsString.Replace(typeFullName, "").Replace(typeLeafName, ""); // This may throw - and that's fine as the user will receive a controlled version // of that error. RegistryView view = (RegistryView)Enum.Parse(typeof(RegistryView), viewAsString, true); if (!NativeMethodsShared.IsWindows && !keyName.StartsWith("HKEY_CURRENT_USER", StringComparison.OrdinalIgnoreCase)) { // Fake common requests to HKLM that we can resolve // See if this asks for a specific SDK var m = RegistrySdkRegex.Value.Match(keyName); if (m.Success && m.Groups.Count >= 1 && valueName.Equals("InstallRoot", StringComparison.OrdinalIgnoreCase)) { return(Path.Combine(NativeMethodsShared.FrameworkBasePath, m.Groups[0].Value) + Path.DirectorySeparatorChar); } return(string.Empty); } using (RegistryKey key = GetBaseKeyFromKeyName(keyName, view, out string subKeyName)) { if (key != null) { using (RegistryKey subKey = key.OpenSubKey(subKeyName, false)) { // If we managed to retrieve the subkey, then move onto locating the value if (subKey != null) { result = subKey.GetValue(valueName); } // We've found a value, so stop looking if (result != null) { break; } } } } } } // We will have either found a result or defaultValue if one wasn't found at this point return(result); }
/// <summary> /// Following function will parse a keyName and returns the basekey for it. /// It will also store the subkey name in the out parameter. /// If the keyName is not valid, we will throw ArgumentException. /// The return value shouldn't be null. /// Taken from: \ndp\clr\src\BCL\Microsoft\Win32\Registry.cs /// </summary> private static RegistryKey GetBaseKeyFromKeyName(string keyName, RegistryView view, out string subKeyName) { if (keyName == null) { throw new ArgumentNullException(nameof(keyName)); } string basekeyName; int i = keyName.IndexOf('\\'); if (i != -1) { basekeyName = keyName.Substring(0, i).ToUpperInvariant(); } else { basekeyName = keyName.ToUpperInvariant(); } RegistryKey basekey = null; switch (basekeyName) { case "HKEY_CURRENT_USER": basekey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, view); break; case "HKEY_LOCAL_MACHINE": basekey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view); break; case "HKEY_CLASSES_ROOT": basekey = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, view); break; case "HKEY_USERS": basekey = RegistryKey.OpenBaseKey(RegistryHive.Users, view); break; case "HKEY_PERFORMANCE_DATA": basekey = RegistryKey.OpenBaseKey(RegistryHive.PerformanceData, view); break; case "HKEY_CURRENT_CONFIG": basekey = RegistryKey.OpenBaseKey(RegistryHive.CurrentConfig, view); break; #if FEATURE_REGISTRYHIVE_DYNDATA case "HKEY_DYN_DATA": basekey = RegistryKey.OpenBaseKey(RegistryHive.DynData, view); break; #endif default: ErrorUtilities.ThrowArgument(keyName); break; } if (i == -1 || i == keyName.Length) { subKeyName = string.Empty; } else { subKeyName = keyName.Substring(i + 1, keyName.Length - i - 1); } return(basekey); }
public static IEnumerable <string> GetRegValueNames(RegistryView view, string regPath, RegistryHive hive = RegistryHive.LocalMachine) { return(RegistryKey.OpenBaseKey(hive, view) ?.OpenSubKey(regPath)?.GetValueNames()); }
private static RegistryKey RegistryKeyLocalMachineX(RegistryParam registryParam, bool writable, bool create, RegistryView registryView) { var localMachineKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView); return(create ? localMachineKey.CreateSubKey(registryParam.RegistrySubKey, writable) : localMachineKey.OpenSubKey(registryParam.RegistrySubKey, writable)); }
public IRegistryKey OpenBaseKey(RegistryHive hive, RegistryView view) { return(new RegistryKeyImpl(RegistryKey.OpenBaseKey(hive, view))); }
public RegistryConfigProvider(RegistryHive hive, RegistryView view, string basePath = "/") : this(CreateUri(hive, view, basePath)) { }