Microsoft.Win32.RegistryKey.Close()

Here are the examples of the csharp api Microsoft.Win32.RegistryKey.Close() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

513 Examples 7

19 Source : Program.cs
with MIT License
from 0x727

public static void RegistryKeyRule(string randomname)
        {
            string regpath = @"Software\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\Microsoft\Windows\UPnP\" + randomname;
            try
            {
                //授予Restore、Backup、TakeOwnership特权
                TokenManipulator.AddPrivilege("SeRestorePrivilege");
                TokenManipulator.AddPrivilege("SeBackupPrivilege");
                TokenManipulator.AddPrivilege("SeTakeOwnershipPrivilege");

                //更改注册表项值的所有者
                RegistryKey subKey = Registry.LocalMachine.OpenSubKey(regpath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);
                RegistrySecurity rs = new RegistrySecurity();
                //设置安全性的所有者为Administrators
                rs.SetOwner(new NTAccount("Administrators"));
                //为注册表项设置权限
                subKey.SetAccessControl(rs);

                //更改注册表项值的权限
                RegistryAccessRule rar = new RegistryAccessRule("Administrators", RegistryRights.FullControl, AccessControlType.Allow);
                rs.AddAccessRule(rar);
                subKey.SetAccessControl(rs);
                subKey.Close();

                RegistryKey rk = Registry.LocalMachine.OpenSubKey(regpath, true);
                //设置Index值为0,隐藏计划任务,默认值为1
                rk.SetValue("Index", 0, RegistryValueKind.DWord);
                rk.Close();

                RegeditKeyExist(regpath);

                string rkl = Registry.LocalMachine + "\\" + regpath;
                Console.WriteLine($"[*] RegistryKey location: \n{rkl}");
            }
            finally
            {
                //删除Restore、Backup、TakeOwnership特权
                TokenManipulator.RemovePrivilege("SeRestorePrivilege");
                TokenManipulator.RemovePrivilege("SeBackupPrivilege");
                TokenManipulator.RemovePrivilege("SeTakeOwnershipPrivilege");

                Console.WriteLine("\n[+] Successfully add scheduled task !");
            }
        }

19 Source : Program.cs
with MIT License
from 0x727

public static void RegeditKeyExist(string regpath)
        {
            string[] subkeyNames;
            RegistryKey sd = Registry.LocalMachine.OpenSubKey(regpath, true);
            subkeyNames = sd.GetValueNames();
            foreach (string keyName in subkeyNames)
            {
                if (keyName == "SD")
                {
                    sd.DeleteValue("SD");
                    sd.Close();
                    return;
                }
            }
            sd.Close();
            return;
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

static void QueryReg()
        {
            try
            {
                string keypath = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU";
                Console.WriteLine("Current HKCU:{0} values", keypath);
                RegistryKey regkey;
                regkey = Registry.CurrentUser.OpenSubKey(keypath, true);
                if (regkey.ValueCount > 0)
                {
                    foreach (string subKey in regkey.GetValueNames())
                    {
                        Console.WriteLine("[+]  Key Name : {0}", subKey);
                        Console.WriteLine("        Value : {0}", regkey.GetValue(subKey).ToString());
                        Console.WriteLine();
                    }
                }
                regkey.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("[-] Error: {0}", ex.Message);
            }
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

static void CleanSingle(string command)
        {
            string keypath = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU";
            string keyvalue = string.Empty;
            string regcmd = string.Empty;
            if (command.EndsWith("\\1"))
            {
                regcmd = command;
            }
            else
            {
                regcmd = string.Format("{0}\\1", command);
            }
             
            try
            {
                RegistryKey regkey;
                regkey = Registry.CurrentUser.OpenSubKey(keypath, true);

                if (regkey.ValueCount > 0)
                {
                    foreach (string subKey in regkey.GetValueNames())
                    {
                        if(regkey.GetValue(subKey).ToString() == regcmd)
                        {
                            keyvalue = subKey;
                            regkey.DeleteValue(subKey);
                            Console.WriteLine(regcmd);
                            Console.WriteLine("[+] Cleaned {0} from HKCU:{1}", command, keypath);
                        }
                    }
                    if(keyvalue != string.Empty)
                    {
                        string mruchars = regkey.GetValue("MRUList").ToString();
                        int index = mruchars.IndexOf(keyvalue);
                        mruchars = mruchars.Remove(index, 1);
                        regkey.SetValue("MRUList", mruchars);
                    }
                }
                regkey.Close();
            }
            catch (ArgumentException)
            {
                Console.WriteLine("[-] Error: Selected Registry value does not exist");
            }
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

static void Clereplacedl()
        {
            try
            {
                string keypath = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU";
                Console.WriteLine("HKCU:{0}", keypath);
                RegistryKey regkey;
                regkey = Registry.CurrentUser.OpenSubKey(keypath, true);
                if (regkey.ValueCount > 0)
                {
                    foreach (string subKey in regkey.GetValueNames())
                    {
                        regkey.DeleteValue(subKey);
                    }
                }
                Console.WriteLine("[+] Cleaned all RunMRU values");
                regkey.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("[-] Error: {0}", ex.Message);
            }
        }

19 Source : DarkFender.cs
with MIT License
from 0xyg3n

public static void DisableFender(bool disableTamperProtection, bool disableDefender)
        {
            if (disableTamperProtection) // once we have TrustedInstaller Permission disable the tamper
            {
                RegistryKey Tamper = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows Defender\Features", true);

                Tamper.SetValue("TamperProtection", 4 , RegistryValueKind.DWord); // 4 means disabled 5 means enabled
                /*var timi = Tamper.GetValue("TamperProtection"); //this was for debug*/
                Tamper.Close();
                /*MessageBox.Show(timi.ToString());*/

                if (disableDefender)
                {
                    RegistryKey PolicyFromDisable = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Policies\Microsoft\Windows Defender", true);

                    try
                    {
                        PolicyFromDisable.GetValue("DisableAntiSpyware");
                        //create a new key 
                        PolicyFromDisable.CreateSubKey("DisableAntiSpyware");
                        PolicyFromDisable.SetValue("DisableAntiSpyware", 1, RegistryValueKind.DWord); // 0 means enabled 1 means disabled
                        /*var timi3 = PolicyFromDisable.GetValue("DisableAntiSpyware");
                        MessageBox.Show(timi3.ToString());*/
                        //set the value
                    }
                    catch (Exception) // if the value does not exist create it
                    {

                        //create a new key 
                        PolicyFromDisable.CreateSubKey("DisableAntiSpyware");
                        PolicyFromDisable.SetValue("DisableAntiSpyware", 1, RegistryValueKind.DWord); // 0 means enabled 1 means disabled
                        /*var timi3 = PolicyFromDisable.GetValue("DisableAntiSpyware");
                        MessageBox.Show(timi3.ToString());*/
                        //set the value

                    }
                }
            }
        }

19 Source : ProxySetting.cs
with GNU General Public License v3.0
from 2dust

public static bool UsedProxy()
        {
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            if (rk.GetValue("ProxyEnable").ToString() == "1")
            {
                rk.Close();
                return true;
            }
            else
            {
                rk.Close();
                return false;
            }
        }

19 Source : ProxySetting.cs
with GNU General Public License v3.0
from 2dust

public static string GetProxyProxyServer()
        {
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            string ProxyServer = rk.GetValue("ProxyServer").ToString();
            rk.Close();
            return ProxyServer;

        }

19 Source : Utils.cs
with GNU General Public License v3.0
from 2dust

public static string RegReadValue(string path, string name, string def)
        {
            RegistryKey regKey = null;
            try
            {
                regKey = Registry.CurrentUser.OpenSubKey(path, false);
                string value = regKey?.GetValue(name) as string;
                if (IsNullOrEmpty(value))
                {
                    return def;
                }
                else
                {
                    return value;
                }
            }
            catch (Exception ex)
            {
                SaveLog(ex.Message, ex);
            }
            finally
            {
                regKey?.Close();
            }
            return def;
        }

19 Source : Utils.cs
with GNU General Public License v3.0
from 2dust

public static void RegWriteValue(string path, string name, object value)
        {
            RegistryKey regKey = null;
            try
            {
                regKey = Registry.CurrentUser.CreateSubKey(path);
                if (IsNullOrEmpty(value.ToString()))
                {
                    regKey?.DeleteValue(name, false);
                }
                else
                {
                    regKey?.SetValue(name, value);
                }
            }
            catch (Exception ex)
            {
                SaveLog(ex.Message, ex);
            }
            finally
            {
                regKey?.Close();
            }
        }

19 Source : dlgSettings.cs
with MIT License
from 86Box

private bool SaveSettings()
        {
            if (cbxLogging.Checked && string.IsNullOrWhiteSpace(txtLogPath.Text))
            {
                DialogResult result = MessageBox.Show("Using an empty or whitespace string for the log path will prevent 86Box from logging anything. Are you sure you want to use this path?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result == DialogResult.No)
                {
                    return false;
                }
            }
            if (!File.Exists(txtEXEdir.Text + "86Box.exe") && !File.Exists(txtEXEdir.Text + @"\86Box.exe"))
            {
                DialogResult result = MessageBox.Show("86Box.exe could not be found in the directory you specified, so you won't be able to use any virtual machines. Are you sure you want to use this path?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result == DialogResult.No)
                {
                    return false;
                }
            }
            try
            {
                RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", true); //Try to open the key first (in read-write mode) to see if it already exists
                if (regkey == null) //Regkey doesn't exist yet, must be created first and then reopened
                {
                    Registry.CurrentUser.CreateSubKey(@"SOFTWARE\86Box");
                    regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", true);
                    regkey.CreateSubKey("Virtual Machines");
                }

                //Store the new values, close the key, changes are saved
                regkey.SetValue("EXEdir", txtEXEdir.Text, RegistryValueKind.String);
                regkey.SetValue("CFGdir", txtCFGdir.Text, RegistryValueKind.String);
                regkey.SetValue("MinimizeOnVMStart", cbxMinimize.Checked, RegistryValueKind.DWord);
                regkey.SetValue("ShowConsole", cbxShowConsole.Checked, RegistryValueKind.DWord);
                regkey.SetValue("MinimizeToTray", cbxMinimizeTray.Checked, RegistryValueKind.DWord);
                regkey.SetValue("CloseToTray", cbxCloseTray.Checked, RegistryValueKind.DWord);
                regkey.SetValue("LaunchTimeout", Convert.ToInt32(txtLaunchTimeout.Text), RegistryValueKind.DWord);
                regkey.SetValue("EnableLogging", cbxLogging.Checked, RegistryValueKind.DWord);
                regkey.SetValue("LogPath", txtLogPath.Text, RegistryValueKind.String);
                regkey.SetValue("EnableGridLines", cbxGrid.Checked, RegistryValueKind.DWord);
                regkey.Close();

                settingsChanged = CheckForChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error has occurred. Please provide the following information to the developer:\n" + ex.Message + "\n" + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            finally
            {
                Get86BoxVersion(); //Get the new exe version in any case
            }
            return true;
        }

19 Source : dlgSettings.cs
with MIT License
from 86Box

private void LoadSettings()
        {
            try
            {
                RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", false); //Open the key as read only

                //If the key doesn't exist yet, fallback to defaults
                if (regkey == null)
                {
                    MessageBox.Show("86Box Manager settings could not be loaded. This is normal if you're running 86Box Manager for the first time. Default values will be used.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    //Create the key and reopen it for write access
                    Registry.CurrentUser.CreateSubKey(@"SOFTWARE\86Box");
                    regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", true);
                    regkey.CreateSubKey("Virtual Machines");

                    txtCFGdir.Text = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\86Box VMs\";
                    txtEXEdir.Text = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + @"\86Box\";
                    cbxMinimize.Checked = false;
                    cbxShowConsole.Checked = true;
                    cbxMinimizeTray.Checked = false;
                    cbxCloseTray.Checked = false;
                    cbxLogging.Checked = false;
                    txtLaunchTimeout.Text = "5000";
                    txtLogPath.Text = "";
                    cbxGrid.Checked = false;
                    btnBrowse3.Enabled = false;
                    txtLogPath.Enabled = false;

                    SaveSettings(); //This will write the default values to the registry
                }
                else
                {
                    txtEXEdir.Text = regkey.GetValue("EXEdir").ToString();
                    txtCFGdir.Text = regkey.GetValue("CFGdir").ToString();
                    txtLaunchTimeout.Text = regkey.GetValue("LaunchTimeout").ToString();
                    txtLogPath.Text = regkey.GetValue("LogPath").ToString();
                    cbxMinimize.Checked = Convert.ToBoolean(regkey.GetValue("MinimizeOnVMStart"));
                    cbxShowConsole.Checked = Convert.ToBoolean(regkey.GetValue("ShowConsole"));
                    cbxMinimizeTray.Checked = Convert.ToBoolean(regkey.GetValue("MinimizeToTray"));
                    cbxCloseTray.Checked = Convert.ToBoolean(regkey.GetValue("CloseToTray"));
                    cbxLogging.Checked = Convert.ToBoolean(regkey.GetValue("EnableLogging"));
                    cbxGrid.Checked = Convert.ToBoolean(regkey.GetValue("EnableGridLines"));
                    txtLogPath.Enabled = cbxLogging.Checked;
                    btnBrowse3.Enabled = cbxLogging.Checked;
                }

                regkey.Close();
            }
            catch (Exception ex)
            {
                txtCFGdir.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents) + @"\86Box VMs";
                txtEXEdir.Text = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + @"\86Box";
                cbxMinimize.Checked = false;
                cbxShowConsole.Checked = true;
                cbxMinimizeTray.Checked = false;
                cbxCloseTray.Checked = false;
                cbxLogging.Checked = false;
                txtLaunchTimeout.Text = "5000";
                txtLogPath.Text = "";
                cbxGrid.Checked = false;
                txtLogPath.Enabled = false;
                btnBrowse3.Enabled = false;
            }
        }

19 Source : dlgSettings.cs
with MIT License
from 86Box

private void ResetSettings()
        {
            RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", true);
            if (regkey == null)
            {
                Registry.CurrentUser.CreateSubKey(@"SOFTWARE\86Box");
                regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box", true);
                regkey.CreateSubKey("Virtual Machines");
            }
            regkey.Close();

            txtCFGdir.Text = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\86Box VMs\";
            txtEXEdir.Text = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + @"\86Box\";
            cbxMinimize.Checked = false;
            cbxShowConsole.Checked = true;
            cbxMinimizeTray.Checked = false;
            cbxCloseTray.Checked = false;
            cbxLogging.Checked = false;
            txtLaunchTimeout.Text = "5000";
            txtLogPath.Text = "";
            cbxGrid.Checked = false;
            txtLogPath.Enabled = false;
            btnBrowse3.Enabled = false;

            settingsChanged = CheckForChanges();
        }

19 Source : dlgSettings.cs
with MIT License
from 86Box

private bool CheckForChanges()
        {
            RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box");

            try
            {
                btnApply.Enabled = (
                    txtEXEdir.Text != regkey.GetValue("EXEdir").ToString() ||
                    txtCFGdir.Text != regkey.GetValue("CFGdir").ToString() ||
                    txtLogPath.Text != regkey.GetValue("LogPath").ToString() ||
                    txtLaunchTimeout.Text != regkey.GetValue("LaunchTimeout").ToString() ||
                    cbxMinimize.Checked != Convert.ToBoolean(regkey.GetValue("MinimizeOnVMStart")) ||
                    cbxShowConsole.Checked != Convert.ToBoolean(regkey.GetValue("ShowConsole")) ||
                    cbxMinimizeTray.Checked != Convert.ToBoolean(regkey.GetValue("MinimizeToTray")) ||
                    cbxCloseTray.Checked != Convert.ToBoolean(regkey.GetValue("CloseToTray")) || 
                    cbxLogging.Checked != Convert.ToBoolean(regkey.GetValue("EnableLogging")) ||
                    cbxGrid.Checked != Convert.ToBoolean(regkey.GetValue("EnableGridLines")));

                return btnApply.Enabled;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
                return true; //For now let's just return true if anything goes wrong
            }
            finally
            {
                regkey.Close();
            }
        }

19 Source : ChromiumBrowser.cs
with MIT License
from acandylevey

public void Register(string Hostname, string ManifestPath)
        {
            string targetKeyPath = regHostnameKeyLocation + Hostname;

            RegistryKey regKey = Registry.CurrentUser.OpenSubKey(targetKeyPath, true);

            if (regKey == null)
                regKey = Registry.CurrentUser.CreateSubKey(targetKeyPath);

            regKey.SetValue("", ManifestPath, RegistryValueKind.String);

            regKey.Close();

            Log.LogMessage("Registered host (" + Hostname + ") with browser " + BrowserName);
        }

19 Source : ChromiumBrowser.cs
with MIT License
from acandylevey

public void Unregister(string Hostname)
        {
            string targetKeyPath = regHostnameKeyLocation + Hostname;

            RegistryKey regKey = Registry.CurrentUser.OpenSubKey(targetKeyPath, true);
            if (regKey != null)
                regKey.DeleteSubKey("", true);
            regKey?.Close();

            Log.LogMessage("Unregistered host (" + Hostname + ") with browser " + BrowserName);
        }

19 Source : KeyUtil.cs
with GNU General Public License v3.0
from ahmed605

public string FindGameDirectory()
        {

            if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), ExecutableName)))
            {
                dir = Directory.GetCurrentDirectory();
            }
            else
            {
                if (ExecutableName == "GTAIV.exe" && File.Exists(@"path.iv") && !StringExtensions.IsNullOrWhiteSpace(File.ReadAllText(@"path.iv")) && File.Exists(Path.Combine(File.ReadAllText(@"path.iv"), ExecutableName)))
                {
                    dir = File.ReadAllText(@"path.iv");
                }
                else
                {
                    if (ExecutableName == "EFLC.exe" && File.Exists(@"path.eflc") && !StringExtensions.IsNullOrWhiteSpace(File.ReadAllText(@"path.eflc")) && File.Exists(Path.Combine(File.ReadAllText(@"path.eflc"), ExecutableName)))
                    {
                        dir = File.ReadAllText(@"path.eflc");
                    }
                    else
                    {
                        var keys = PathRegistryKeys;
                        foreach (var s in keys)
                        {
                            RegistryKey key;
                            if ((key = Registry.LocalMachine.OpenSubKey(s)) != null)
                            {
                                if (key.GetValue("InstallFolder") != null && File.Exists(Path.Combine(key.GetValue("InstallFolder").ToString(), ExecutableName)))
                                {
                                    dir = key.GetValue("InstallFolder").ToString();
                                    key.Close();
                                    break;
                                }
                                else
                                {
                                    var fbd = new VistaFolderBrowserDialog();
                                    fbd.Description = "Select game folder";
                                    //DialogResult result = fbd.ShowDialog();
                                    if (fbd.ShowDialog() == DialogResult.OK && !StringExtensions.IsNullOrWhiteSpace(fbd.SelectedPath))
                                    {
                                        dir = fbd.SelectedPath;
                                        break;
                                    }
                                    else
                                    {
                                        MessageBox.Show("Please select game folder.");
                                        Application.Exit();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return dir;
        }

19 Source : CloudServiceFunctions.cs
with MIT License
from AlbertMN

public static string GetGoogleDriveFolder() {
            //New Google Drive check first
            string registryKey = @"Software\Google\DriveFS";
            RegistryKey key = Registry.CurrentUser.OpenSubKey(registryKey);

            if (key != null || Directory.Exists(Environment.ExpandEnvironmentVariables("%programfiles%") + @"\Google\Drive File Stream")) {
                //New google Drive seems to be installed
                DriveInfo[] allDrives = DriveInfo.GetDrives();

                //Check if it's a virual drive
                foreach (DriveInfo d in allDrives) {
                    if (d.VolumeLabel == "Google Drive") {
                        string check = Path.Combine(d.Name, "My Drive");
                        if (Directory.Exists(check)) {
                            return check;
                        }
                    }
                }

                //Not a virtual drive, check the user's folder
                string userDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                if (Directory.Exists(userDir)) {
                    foreach (string dir in Directory.GetDirectories(userDir)) {
                        if (dir.Contains("My Drive")) {
                            //Pretty sure it's Google Drive... But bad practice maybe...?
                            return dir;
                        }
                    }
                }


                return "partial";
            }

            //No? Check the old one
            registryKey = @"Software\Google\Drive";
            key = Registry.CurrentUser.OpenSubKey(registryKey);
            if (key != null) {
                string installed = key.GetValue("Installed").ToString();
                key.Close();
                if (installed != null) {
                    if (installed == "True") {
                        string checkPath = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Google Drive");
                        if (Directory.Exists(checkPath)) {
                            return checkPath;
                        }
                        return "partial";
                    }
                }
            }
            return "";
        }

19 Source : MainProgram.cs
with MIT License
from AlbertMN

public static bool ApplicationInstalled(string c_name) {
            string displayName;

            string registryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey);
            if (key != null) {
                foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName))) {
                    displayName = subkey.GetValue("DisplayName") as string;
                    if (displayName != null && displayName.Contains(c_name)) {
                        return true;
                    }
                }
                key.Close();
            }

            registryKey = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
            key = Registry.LocalMachine.OpenSubKey(registryKey);
            if (key != null) {
                foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName))) {
                    displayName = subkey.GetValue("DisplayName") as string;
                    if (displayName != null && displayName.Contains(c_name)) {
                        return true;
                    }
                }
                key.Close();
            }
            return false;
        }

19 Source : AccountService.cs
with MIT License
from aliprogrammer69

public void Set(AuthConfiguration config) {
            if (config == null) {
                throw new System.NullReferenceException("Config must have value");
            }
            CurrentConfig = config;

            RegistryKey authKey = Registry.CurrentUser.CreateSubKey(Consts.AuthConfigRegKey, true);
            authKey.SetValue("auth", Encrypt(config), RegistryValueKind.Binary);
            authKey.Close();
        }

19 Source : SettingsKey.cs
with Apache License 2.0
from AmpScm

public void Dispose()
        {
            m_Key.Close();
        }

19 Source : IISApplicationController.cs
with GNU General Public License v3.0
from AndreiFedarets

private void SetKeys()
        {
            RegistryKey key = Registry.Users.OpenSubKey(KeyName, true);

            Dictionary<string, string> variables = GetEnvironmentVariables();
            foreach (string item in variables.Keys)
            {
                key.SetValue(item, variables[item]);
            }

            key.Close();
        }

19 Source : IISApplicationController.cs
with GNU General Public License v3.0
from AndreiFedarets

private void DeleteKeys()
        {
            RegistryKey key = Registry.Users.OpenSubKey(KeyName, true);

            foreach (string item in GetEnvironmentVariables().Keys)
            {
                key.DeleteValue(item, false);
            }

            key.Close();
        }

19 Source : WebBrowserHelper.cs
with MIT License
from anoyetta

public static void SetUseNewestWebBrowser()
        {
            var filename = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
            if (filename.Contains("vhost"))
            {
                filename = filename.Substring(0, filename.IndexOf('.') + 1) + "exe";
            }

            var key1 = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION");
            var key2 = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BEHAVIORS");
            key1?.SetValue(filename, 11001, RegistryValueKind.DWord);
            key2?.SetValue(filename, 11001, RegistryValueKind.DWord);
            key1?.Close();
            key2?.Close();
        }

19 Source : Steam.cs
with GNU General Public License v3.0
from Artentus

private static bool TryGetSteamPathWin32([NotNullWhen(true)] out string? path)
        {
            path = null;

            RegistryKey? softwareKey = null;
            try
            {
                string softwarePath = Environment.Is64BitProcess ? @"SOFTWARE\WOW6432Node" : "SOFTWARE";
                softwareKey = Registry.LocalMachine.OpenSubKey(softwarePath, false);
                if (softwareKey is null) return false;

                using var key = softwareKey.OpenSubKey(@"Valve\Steam");
                var obj = key?.GetValue("InstallPath");
                path = obj as string;
                if (string.IsNullOrEmpty(path)) return false;

                return Directory.Exists(path);
            }
            catch
            {
                return false;
            }
            finally
            {
                softwareKey?.Close();
            }
        }

19 Source : UnZipRarSystem.cs
with GNU General Public License v3.0
from arunsatyarth

private string LookForInstalledWinrar()
        {
            string objRarPath = "";
            try
            {
                RegistryKey objRegKey;
                objRegKey = Registry.ClreplacedesRoot.OpenSubKey("WinRAR\\Shell\\Open\\Command");

                Object obj = objRegKey.GetValue("");

                objRarPath = obj.ToString();
                objRarPath = objRarPath.Substring(1, objRarPath.Length - 7);

                objRegKey.Close();
                FileInfo winrar = new FileInfo(objRarPath);
                if (!winrar.Exists)
                    throw new Exception("File not found");
            }
            catch (Exception e)
            {
                return "";
            }
            return objRarPath;
        }

19 Source : ModHandler.cs
with MIT License
from AstroTechies

private string CheckRegistryForMicrosoftStorePath()
        {
            RegistryKey key1 = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).OpenSubKey(@"Software\Clreplacedes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\Repository\Packages"); // SystemEraSoftworks.29415440E1269_1.16.70.0_x64__ftk5pbg2rayv2
            if (key1 == null) return null;

            RegistryKey goalKey = null;
            foreach (string k in key1.GetSubKeyNames())
            {
                if (k.StartsWith("SystemEraSoftworks"))
                {
                    goalKey = key1.OpenSubKey(k);
                    break;
                }
            }
            key1.Close();
            if (goalKey == null) return null;

            string packageID = goalKey.GetValue("PackageID") as string;
            string rootFolder = goalKey.GetValue("PackageRootFolder") as string;
            goalKey.Close();

            if (!string.IsNullOrEmpty(packageID))
            {
                string[] idBits = packageID.Split('_');
                if (idBits.Length >= 2) MicrosoftRuntimeID = idBits[0] + "_" + idBits[idBits.Length - 1];
            }
            return rootFolder;
        }

19 Source : ModHandler.cs
with MIT License
from AstroTechies

private string CheckRegistryForSteamPath(int appID)
        {
            string decidedSteamPath = null;
            RegistryKey key1 = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).OpenSubKey(@"SOFTWARE\Wow6432Node\Valve\Steam");
            RegistryKey key2 = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Valve\Steam");
            if (key1 != null)
            {
                object o = key1.GetValue("SteamPath");
                if (o != null) decidedSteamPath = o as string;
            }
            else if (key2 != null)
            {
                object o = key2.GetValue("SteamPath");
                if (o != null) decidedSteamPath = o as string;
            }

            if (key1 != null) key1.Close();
            if (key2 != null) key2.Close();

            if (decidedSteamPath == null) return null;

            List<string> potentialInstallDirs = new List<string>();
            potentialInstallDirs.Add(decidedSteamPath);

            try
            {
                using (StreamReader f = new StreamReader(Path.Combine(decidedSteamPath, "steamapps", "libraryfolders.vdf")))
                {
                    string vdfEntry = null;
                    while ((vdfEntry = f.ReadLine()) != null)
                    {
                        Match m = vdfEntryReader.Match(vdfEntry);
                        if (m.Groups.Count == 3)
                        {
                            potentialInstallDirs.Add(m.Groups[2].Value.Replace(@"\\", @"\").Replace("\"", ""));
                        }
                    }
                }
            }
            catch (IOException) { }

            try
            {
                using (StreamReader f = new StreamReader(Path.Combine(decidedSteamPath, "config", "config.vdf")))
                {
                    string vdfEntry = null;
                    while ((vdfEntry = f.ReadLine()) != null)
                    {
                        Match m = vdfEntryReader.Match(vdfEntry);
                        if (m.Groups.Count == 3 && m.Groups[1].Value.StartsWith("BaseInstallFolder_"))
                        {
                            potentialInstallDirs.Add(m.Groups[2].Value.Replace(@"\\", @"\").Replace("\"", ""));
                        }
                    }
                }
            }
            catch (IOException) { }

            List<string> astroInstallDirs = new List<string>();
            foreach (string installPath in potentialInstallDirs)
            {
                string tempAstroInstallDir = null;
                if ((tempAstroInstallDir = CheckSteamPathForGame(appID, installPath)) != null)
                {
                    astroInstallDirs.Add(tempAstroInstallDir);
                }
            }

            if (astroInstallDirs.Count > 0)
            {
                return astroInstallDirs[0];
            }

            return null;
        }

19 Source : CustomAction.cs
with Apache License 2.0
from awslabs

[CustomAction]
        public static ActionResult UpgradePowershellInstalledKinesisTap(Session session)
        {
            session.Log("Begin upgrading Powershell installed KinesisTap");
            //Need to run UpgradePowershellInstalledKinesisTap.SetProperty custom action first to set the value

            string serviceName = session.CustomActionData["SERVICENAME"];
            RegistryKey registryKeyHKLM = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
            string keyPath = $@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{serviceName}";

            try
            {
                RegistryKey key = registryKeyHKLM.OpenSubKey(keyPath, true);
 
                string valueData;
                if (key != null && (valueData = (string)key.GetValue("UninstallString")) != null)
                {
                    // KinesisTap is PowerShell installed, delete the registery key
                    if (valueData.Contains("uninstall.ps1"))
                    {
                        session.Log($@"KinesisTap found is PowerShell installed.");
                        session.Log($@"Deleting registry 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{serviceName}'.");
                        key.Close();
                        registryKeyHKLM.DeleteSubKeyTree(keyPath);
                    }
                }
            }
            catch (Exception ex)
            {
                session.Log($"Failed to upgrade from Powershell installed KinesisTap: {ex.Message}");
                return ActionResult.Failure;
            }
            finally
            {
                registryKeyHKLM.Close();
            }

            session.Log("Finish upgrading Powershell installed KinesisTap");
            return ActionResult.Success;
        }

19 Source : AyFuncFileExtRegister.cs
with MIT License
from ay2015

private void SetValue(RegistryKey root, string subKey, object keyValue, string valueName)
        {
            bool hreplacedubKey = ((subKey != null) && (subKey.Length > 0));
            RegistryKey key = root;

            try
            {
                if (hreplacedubKey) key = root.CreateSubKey(subKey);
                key.SetValue(valueName, keyValue);
            }
            finally
            {
                if (hreplacedubKey && (key != null)) key.Close();
            }
        }

19 Source : AyFuncRegisterTable.cs
with MIT License
from ay2015

public object Get(string name)
        {
            string registData;
            RegistryKey hkml = Registry.LocalMachine;
            RegistryKey software = hkml.OpenSubKey("SOFTWARE", true);
            RegistryKey aimdir = software.OpenSubKey(AyFuncConfig.TableSoftwareName, true);
            registData = aimdir.GetValue(name).ToString();
            hkml.Close();
            return registData;
        }

19 Source : AyFuncRegisterTable.cs
with MIT License
from ay2015

public bool IsExist(string name)
        {
            string[] subkeyNames;
            RegistryKey hkml = Registry.LocalMachine;
            RegistryKey software = hkml.OpenSubKey("SOFTWARE");
            subkeyNames = software.GetSubKeyNames();
            //取得该项下所有子项的名称的序列,并传递给预定的数组中  
            foreach (string keyName in subkeyNames)
            //遍历整个数组  
            {
                if (keyName == name)
                //判断子项的名称  
                {
                    hkml.Close();
                    return true;
                }
            }
            hkml.Close();
            return false;
        }

19 Source : ShellHost.cs
with GNU General Public License v3.0
from belowaverage-org

private void MsMiOptionsSubItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mi = (ToolStripMenuItem)sender;
            mi.Checked = !mi.Checked;
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced", true);
            string tag = (string)mi.Tag;
            string name = tag.Substring(1);
            int set = 0;
            if (tag[0] == '0' && mi.Checked) set = 1;
            if (tag[0] == '1' && !mi.Checked) set = 1;
            key.SetValue(name, set);
            key.Close();
            MessageBox.Show("In order for these changes to take effect, right click anywhere in the file explorer window and select \"Refresh\".", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

19 Source : Run.cs
with GNU General Public License v3.0
from belowaverage-org

public void LoadMRU()
        {
            RegistryKey reg = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU");
            if (reg == null) return;
            string sMruList = (string)reg.GetValue("MRUList");
            if (sMruList == null) return;
            sMruList.ToCharArray().CopyTo(MRUList, 0);
            foreach (char item in MRUList)
            {
                if (item == '\0') continue;
                int mruKeyIndex = Array.IndexOf(MRUKeys, item);
                if (mruKeyIndex == -1) continue;
                MRUVals[mruKeyIndex] = (string)reg.GetValue(item.ToString());
            }
            reg.Close();
        }

19 Source : Run.cs
with GNU General Public License v3.0
from belowaverage-org

public void SaveMRU()
        {
            RegistryKey reg = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU", true);
            string sMruList = "";
            foreach (char letter in MRUList)
            {
                if (letter == '\0') continue;
                sMruList += letter;
            }
            reg.SetValue("MRUList", sMruList);
            foreach (char item in sMruList)
            {
                int mruKeyIndex = Array.IndexOf(MRUKeys, item);
                if (mruKeyIndex == -1) continue;
                reg.SetValue(item.ToString(), MRUVals[mruKeyIndex]);
            }
            reg.Close();
        }

19 Source : ShellHost.cs
with GNU General Public License v3.0
from belowaverage-org

private void MsMiOptions_DropDownOpening(object sender, EventArgs e)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced", false);
            foreach (ToolStripMenuItem mi in MsMiOptions.DropDownItems)
            {
                string tag = (string)mi.Tag;
                string name = tag.Substring(1);
                object set = key.GetValue(name);
                if (set == null) continue;
                if (tag[0] == '0')
                {
                    mi.Checked = ((int)set == 1);
                }
                else
                {
                    mi.Checked = ((int)set == 0);
                }
            }
            key.Close();
        }

19 Source : Uninstall.xaml.cs
with GNU General Public License v2.0
from BlackTasty

private void RemoveFromRegistry()
        {
            RegistryKey edgeKey = Registry.CurrentUser.OpenSubKey(@"Software\" + GlobalValues.AppName, false);
            string guidPath = edgeKey.GetValue("GUID").ToString();
            edgeKey.Close();
            Registry.CurrentUser.DeleteSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + guidPath);
        }

19 Source : Install.xaml.cs
with GNU General Public License v2.0
from BlackTasty

private void CreateSubKey(string subKey, string value = null)
        {
            RegistryKey key = Registry.CurrentUser.CreateSubKey(subKey);
            if (value != null)
                key.SetValue("", value);
            key.Close();
        }

19 Source : UninstallEntry.cs
with GNU General Public License v2.0
from BlackTasty

public void CreateUninstaller(double estimatedSize)
        {
            try
            {
                try
                {
                    if (Registry.CurrentUser.OpenSubKey(UninstallRegKeyPath) == null)
                        Registry.CurrentUser.CreateSubKey(UninstallRegKeyPath);
                }
                catch
                {
                    Registry.CurrentUser.CreateSubKey(UninstallRegKeyPath);
                }

                using (RegistryKey parent = Registry.CurrentUser.OpenSubKey(
                             UninstallRegKeyPath, true))
                {
                    if (parent == null)
                    {
                        throw new Exception("Uninstall registry key not found.");
                    }
                    RegistryKey key = null;

                    try
                    {
                        key = parent.OpenSubKey(GlobalValues.AppName, true) ??
                              parent.CreateSubKey(GlobalValues.AppName);

                        if (key == null)
                        {
                            throw new Exception(string.Format("Unable to create uninstaller \"{0}\\{1}\"", UninstallRegKeyPath, GlobalValues.AppName));
                        }

                        replacedembly asm = GetType().replacedembly;
                        Version v = asm.GetName().Version;
                        string exe = GlobalValues.InstallationPath + GlobalValues.AppName + ".exe";

                        key.SetValue("ApplicationVersion", v.ToString());
                        key.SetValue("HelpLink", "https://osu.ppy.sh/forum/t/756318");
                        key.SetValue("DisplayIcon", exe);
                        key.SetValue("DisplayName", GlobalValues.AppName);
                        key.SetValue("DisplayVersion", v.ToString(2));
                        key.SetValue("EstimatedSize", estimatedSize, RegistryValueKind.DWord);
                        key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd"));
                        key.SetValue("NoRepair", 1, RegistryValueKind.DWord);
                        key.SetValue("NoModify", 1, RegistryValueKind.DWord);
                        key.SetValue("Publisher", "BlackTasty");
                        key.SetValue("URLInfoAbout", "");
                        key.SetValue("InstallLocation", GlobalValues.InstallationPath);
                        key.SetValue("UninstallString", GlobalValues.InstallationPath + "uninstall.exe");
                    }
                    finally
                    {
                        if (key != null)
                        {
                            key.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(
                    "An error occurred writing uninstall information to the registry. The application has been fully installed but can only be uninstalled manually through deleting the files located in " + GlobalValues.InstallationPath + ".",
                    ex);
            }
        }

19 Source : UninstallEntry.cs
with GNU General Public License v2.0
from BlackTasty

public void CreateUninstaller(double estimatedSize)
        {
            try
            {
                try
                {
                    if (Registry.CurrentUser.OpenSubKey(UninstallRegKeyPath) == null)
                        Registry.CurrentUser.CreateSubKey(UninstallRegKeyPath);
                }
                catch
                {
                    Registry.CurrentUser.CreateSubKey(UninstallRegKeyPath);
                }

                using (RegistryKey parent = Registry.CurrentUser.OpenSubKey(
                             UninstallRegKeyPath, true))
                {
                    if (parent == null)
                    {
                        throw new Exception("Uninstall registry key not found.");
                    }
                    RegistryKey key = null;

                    try
                    {
                        key = parent.OpenSubKey(GlobalValues.AppName, true) ??
                              parent.CreateSubKey(GlobalValues.AppName);

                        if (key == null)
                        {
                            throw new Exception(string.Format("Unable to create uninstaller \"{0}\\{1}\"", UninstallRegKeyPath, GlobalValues.AppName));
                        }

                        replacedembly asm = GetType().replacedembly;
                        Version v = asm.GetName().Version;
                        string exe = GlobalValues.InstallationPath + GlobalValues.AppName + ".exe";

                        key.SetValue("ApplicationVersion", v.ToString());
                        key.SetValue("HelpLink", "https://osu.ppy.sh/forum/t/756318");
                        key.SetValue("DisplayIcon", exe);
                        key.SetValue("DisplayName", GlobalValues.AppName);
                        key.SetValue("DisplayVersion", v.ToString(2));
                        key.SetValue("EstimatedSize", estimatedSize, RegistryValueKind.DWord);
                        key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd"));
                        key.SetValue("NoRepair", 1, RegistryValueKind.DWord);
                        key.SetValue("NoModify", 1, RegistryValueKind.DWord);
                        key.SetValue("Publisher", "BlackTasty");
                        key.SetValue("URLInfoAbout", "");
                        key.SetValue("InstallLocation", GlobalValues.InstallationPath);
                        key.SetValue("UninstallString", GlobalValues.InstallationPath + "uninstall.exe");
                    }
                    finally
                    {
                        if (key != null)
                        {
                            key.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(
                    "An error occurred writing uninstall information to the registry. " +
                    "The application has been fully installed but can only be uninstalled manually through " +
                    "deleting the files located in " + GlobalValues.InstallationPath + ".",
                    ex);
            }
        }

19 Source : Uninstall.xaml.cs
with GNU General Public License v2.0
from BlackTasty

private void RemoveFromRegistry()
        {
            RegistryKey edgeKey = Registry.CurrentUser.OpenSubKey(@"Software\" + GlobalValues.AppName, false);
            string guidPath = edgeKey.GetValue("GUID").ToString();
            edgeKey.Close();
            Registry.CurrentUser.DeleteSubKey(@"Software\" + GlobalValues.AppName);
            Registry.CurrentUser.DeleteSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + guidPath);
        }

19 Source : RegTrustedInstaller.cs
with MIT License
from BluePointLilac

public static void TakeRegKeyOwnerShip(string regPath)
        {
            if(regPath.IsNullOrWhiteSpace()) return;
            RegistryKey key = null;
            WindowsIdenreplacedy id = null;
            //利用试错判断是否有写入权限
            try { key = RegistryEx.GetRegistryKey(regPath, true); }
            catch
            {
                try
                {
                    //获取当前用户的ID
                    id = WindowsIdenreplacedy.GetCurrent();

                    //添加TakeOwnership特权
                    bool flag = NativeMethod.TrySetPrivilege(NativeMethod.TakeOwnership, true);
                    if(!flag) throw new PrivilegeNotHeldException(NativeMethod.TakeOwnership);

                    //添加恢复特权(必须这样做才能更改所有者)
                    flag = NativeMethod.TrySetPrivilege(NativeMethod.Restore, true);
                    if(!flag) throw new PrivilegeNotHeldException(NativeMethod.Restore);

                    //打开没有权限的注册表路径
                    key = RegistryEx.GetRegistryKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);

                    RegistrySecurity security = key.GetAccessControl(AccessControlSections.All);

                    //得到真正所有者
                    //IdenreplacedyReference oldId = security.GetOwner(typeof(SecurityIdentifier));
                    //SecurityIdentifier siTrustedInstaller = new SecurityIdentifier(oldId.ToString());

                    //使进程用户成为所有者
                    security.SetOwner(id.User);
                    key.SetAccessControl(security);

                    //添加完全控制
                    RegistryAccessRule fullAccess = new RegistryAccessRule(id.User, RegistryRights.FullControl,
                        InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
                    security.AddAccessRule(fullAccess);
                    key.SetAccessControl(security);

                    //注册表操作(写入、删除)
                    //key.SetValue("temp", "");//示例

                    //恢复原有所有者
                    //security.SetOwner(siTrustedInstaller);
                    //key.SetAccessControl(security);

                    //收回原有权利
                    //security.RemoveAccessRule(fullAccess);
                    //key.SetAccessControl(security);

                    ///得到真正所有者、注册表操作、恢复原有所有者、收回原有权利,这四部分在原文中没有被注释掉
                    ///但是如果保留这四部分,会在恢复原有所有者这一步抛出异常,提示没有权限,
                    ///不过我发现经过上面的操作,虽然无法还原所有者权限,但是已经获取了注册表权限
                    ///即已经将TrustedInstaller权限更改为当前管理员用户权限,我要的目的已经达到了
                }
                catch { }
            }
            finally { key?.Close(); id?.Dispose(); }
        }

19 Source : Settings.cs
with MIT License
from BoltBait

internal static void CloseRegKey()
        {
            if (regKey != null)
            {
                regKey.Close();
                regKey.Dispose();
                regKey = null;
            }
        }

19 Source : AutostartManager.cs
with GNU General Public License v3.0
from BornToBeRoot

public static void Enable()
        {
            var registryKey = Registry.CurrentUser.OpenSubKey(RunKeyCurrentUser, true);

            var command = $"{ConfigurationManager.Current.ApplicationFullName} {CommandLineManager.ParameterAutostart}";

            if (registryKey == null)
                return; // LOG

            registryKey.SetValue(ConfigurationManager.Current.ApplicationName, command);
            registryKey.Close();
        }

19 Source : AutostartManager.cs
with GNU General Public License v3.0
from BornToBeRoot

public static void Disable()
        {
            var registryKey = Registry.CurrentUser.OpenSubKey(RunKeyCurrentUser, true);

            if (registryKey == null)
                return; // LOG

            registryKey.DeleteValue(ConfigurationManager.Current.ApplicationName);
            registryKey.Close();
        }

19 Source : FileAssociationsManager.cs
with GNU General Public License v3.0
from BRH-Media

public static bool Setreplacedociation(string extension, string progId, string fileTypeDescription, string applicationFilePath)
        {
            var madeChanges = false;

            //get rid of explorer override
            var currentUser = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\" + extension, true);
            currentUser?.DeleteSubKey("UserChoice", false);
            currentUser?.Close();

            madeChanges |= SetKeyDefaultValue(@"Software\Clreplacedes\" + extension, progId);
            madeChanges |= SetKeyDefaultValue(@"Software\Clreplacedes\" + progId, fileTypeDescription);
            madeChanges |= SetKeyDefaultValue($@"Software\Clreplacedes\{progId}\shell\open\command", "\"" + applicationFilePath + "\" \"%1\"");
            return madeChanges;
        }

19 Source : CustomAction.cs
with Apache License 2.0
from BuffettCode

[CustomAction]
        public static ActionResult CaRegisterAddIn(Session session)
        {
            string szOfficeRegKeyVersions = string.Empty;
            string szBaseAdreplacedey = @"Software\Microsoft\Office\";
            string szXll32Bit = string.Empty;
            string szXll64Bit = string.Empty;
            string szXllToRegister = string.Empty;
            string szFolder = string.Empty;
            int nOpenVersion;
            double nVersion;
            bool bFoundOffice = false;
            List<string> lstVersions;

            try
            {
                session.Log("Enter try block of CaRegisterAddIn");

                szOfficeRegKeyVersions = session["OFFICEREGKEYS"];
                szXll32Bit = session["XLL32"];
                szXll64Bit = session["XLL64"];
                szFolder = session["AddinFolder"];

                szXll32Bit = szFolder.ToString() + szXll32Bit.ToString();
                szXll64Bit = szFolder.ToString() + szXll64Bit.ToString();

                if (szOfficeRegKeyVersions.Length > 0)
                {
                    lstVersions = szOfficeRegKeyVersions.Split(',').ToList();

                    foreach (string szOfficeVersionKey in lstVersions)
                    {
                        nVersion = double.Parse(szOfficeVersionKey, NumberStyles.Any, CultureInfo.InvariantCulture);

                        session.Log("Retrieving Registry Information for : " + szBaseAdreplacedey + szOfficeVersionKey);

                        // get the OPEN keys from the Software\Microsoft\Office\[Version]\Excel\Options key, skip if office version not found.
                        if (Registry.CurrentUser.OpenSubKey(szBaseAdreplacedey + szOfficeVersionKey, false) == null)
                        {
                            session.Log("Retrieving LocalMachine registry key for : " + szBaseAdreplacedey + szOfficeVersionKey);
                            if (Registry.LocalMachine.OpenSubKey(szBaseAdreplacedey + szOfficeVersionKey, false) != null)
                            {
                                session.Log("Create registry key for : " + szBaseAdreplacedey + szOfficeVersionKey + @"\Excel\Options");
                                Registry.CurrentUser.CreateSubKey(szBaseAdreplacedey + szOfficeVersionKey + @"\Excel\Options");
                            }
                        }

                        if (Registry.CurrentUser.OpenSubKey(szBaseAdreplacedey + szOfficeVersionKey, false) != null)
                        {
                            string szKeyName = szBaseAdreplacedey + szOfficeVersionKey + @"\Excel\Options";

                            szXllToRegister = GetAddInName(szXll32Bit, szXll64Bit, szOfficeVersionKey, nVersion);

                            RegistryKey rkExcelXll = Registry.CurrentUser.OpenSubKey(szKeyName, true);

                            if (szXllToRegister != string.Empty && rkExcelXll != null)
                            {
                                string[] szValueNames = rkExcelXll.GetValueNames();
                                bool bIsOpen = false;
                                int nMaxOpen = -1;

                                // check every value for OPEN keys
                                foreach (string szValueName in szValueNames)
                                {
                                    // if there are already OPEN keys, determine if our key is installed
                                    if (szValueName.StartsWith("OPEN"))
                                    {
                                        nOpenVersion = int.TryParse(szValueName.Substring(4), NumberStyles.Any, CultureInfo.InvariantCulture, out nOpenVersion) ? nOpenVersion : 0;
                                        int nNewOpen = szValueName == "OPEN" ? 0 : nOpenVersion;
                                        if (nNewOpen > nMaxOpen)
                                        {
                                            nMaxOpen = nNewOpen;
                                        }

                                        // if the key is our key, set the open flag
                                        //NOTE: this line means if the user has changed its office from 32 to 64 (or conversly) without removing the addin then we will not update the key properly
                                        //The user will have to uninstall addin before installing it again
                                        if (rkExcelXll.GetValue(szValueName).ToString().Contains(szXllToRegister))
                                        {
                                            bIsOpen = true;
                                        }
                                    }
                                }

                                // if adding a new key
                                if (!bIsOpen)
                                {
                                    if (nMaxOpen == -1)
                                    {
                                        rkExcelXll.SetValue("OPEN", "/R \"" + szXllToRegister + "\"");
                                    }
                                    else
                                    {
                                        rkExcelXll.SetValue("OPEN" + (nMaxOpen + 1).ToString(), "/R \"" + szXllToRegister + "\"");
                                    }
                                    rkExcelXll.Close();
                                }
                                bFoundOffice = true;
                            }
                            else
                            {
                                session.Log("Unable to retrieve key for : " + szKeyName);
                            }
                        }
                        else
                        {
                            session.Log("Unable to retrieve registry Information for : " + szBaseAdreplacedey + szOfficeVersionKey);
                        }
                    }
                }

                session.Log("End CaRegisterAddIn");
            }
            catch (System.Security.SecurityException ex)
            {
                session.Log("CaRegisterAddIn SecurityException" + ex.Message);
                bFoundOffice = false;
            }
            catch (System.UnauthorizedAccessException ex)
            {
                session.Log("CaRegisterAddIn UnauthorizedAccessException" + ex.Message);
                bFoundOffice = false;
            }
            catch (Exception ex)
            {
                session.Log("CaRegisterAddIn Exception" + ex.Message);
                bFoundOffice = false;
            }

            return bFoundOffice ? ActionResult.Success : ActionResult.Failure;
        }

19 Source : MainWindow.xaml.cs
with MIT License
from builtbybel

private void CheckAU()
        {
            RegistryKey RegHKLM = Registry.LocalMachine;
            RegistryKey updateRegHKLM;

            if (RegHKLM.OpenSubKey(@"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU") != null)
            {
                updateRegHKLM = RegHKLM.OpenSubKey(@"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU");

                if (updateRegHKLM.GetValueNames().Contains("AUOptions"))
                {
                    if ((Int32)updateRegHKLM.GetValue("AUOptions") == 2) { _checkAU.IsChecked = true; _checkAU.Content = "*Automatic updates on this device are turned off."; }
                    else { _checkAU.IsChecked = false; _checkAU.Content = "*Automatic updates on this device are turned on."; }
                }

                updateRegHKLM.Close();
            }
        }

19 Source : StartupRunner.cs
with Apache License 2.0
from cairoshell

private List<string> GetDisallowedItems(StartupLocation location, StartupEntryScope? overrideScope = null)
        {
            List<string> disallowedApps = new List<string>();

            if (!string.IsNullOrEmpty(location.ApprovedLocation))
            {
                StartupEntryScope scope = overrideScope ?? location.Scope;
                RegistryKey[] roots = ScopeToRoots(scope);

                foreach (var root in roots)
                {
                    try
                    {
                        RegistryKey registryKey =
                            root.OpenSubKey(location.ApprovedLocation, false);

                        if (registryKey != null && registryKey.ValueCount > 0)
                        {
                            foreach (var valueName in registryKey.GetValueNames())
                            {
                                if (((byte[])registryKey.GetValue(valueName))[0] % 2 != 0) // if value is odd number, item is disabled
                                {
                                    disallowedApps.Add(valueName);
                                    ShellLogger.Debug($"StartupRunner: Skipping disabled entry: {valueName}");
                                }
                            }
                        }

                        // close key when finished
                        registryKey?.Close();
                    }
                    catch
                    {
                        ShellLogger.Warning($"StartupRunner: Unable to load allowed startup items list from registry key {location.ApprovedLocation}");
                    }
                }
            }

            return disallowedApps;
        }

19 Source : StartupRunner.cs
with Apache License 2.0
from cairoshell

private List<StartupEntry> GetAppsFromRegistryKey(StartupLocation location)
        {
            RegistryKey[] roots = ScopeToRoots(location.Scope);
            List<StartupEntry> startupApps = new List<StartupEntry>();

            foreach (var root in roots)
            {
                bool isRunOnce = location.Location.Contains("RunOnce");

                try
                {
                    if (isRunOnce && root == Registry.LocalMachine)
                        continue; // skip HKLM RunOnce since we cannot delete these items, and would run them each startup

                    RegistryKey registryKey =
                        root.OpenSubKey(location.Location, root == Registry.CurrentUser); // open as writeable if HKCU

                    if (registryKey != null && registryKey.ValueCount > 0)
                    {
                        // get list of disallowed entries
                        List<string> disallowedItems = GetDisallowedItems(location, root == Registry.LocalMachine ? StartupEntryScope.Machine : StartupEntryScope.User);

                        // add items from registry key
                        foreach (var valueName in registryKey.GetValueNames())
                        {
                            // only add items that are not disabled
                            if (!disallowedItems.Contains(valueName))
                            {
                                startupApps.Add(new StartupEntry
                                {
                                    Location = location,
                                    Path = ((string)registryKey.GetValue(valueName)).Replace("\"", "")
                                });

                                // if this is a runonce key, remove the value after we grab it
                                if (isRunOnce)
                                {
                                    try
                                    {
                                        registryKey.DeleteValue(valueName);
                                    }
                                    catch
                                    {
                                        ShellLogger.Warning($"StartupRunner: Unable to delete RunOnce startup item {valueName}");
                                    }
                                }
                            }
                        }
                    }

                    // close key when finished
                    registryKey?.Close();
                }
                catch
                {
                    ShellLogger.Warning($"StartupRunner: Unable to load startup items from registry key {location.Location}");
                }
            }

            return startupApps;
        }

See More Examples