Microsoft.Win32.RegistryKey.CreateSubKey(string)

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

775 Examples 7

19 View Source File : DarkFender.cs
License : MIT License
Project Creator : 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 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 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 View Source File : dlgSettings.cs
License : MIT License
Project Creator : 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 View Source File : dlgSettings.cs
License : MIT License
Project Creator : 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 View Source File : dlgSettings.cs
License : MIT License
Project Creator : 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 View Source File : ChromiumBrowser.cs
License : MIT License
Project Creator : 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 View Source File : RegistryHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static RegistryKey GetQFErpRootKey()
        {
            using (var root = RegistryKey.OpenBaseKey(RegistryHive.CurrentConfig, RegistryView.Default))
            {
                var r = root.OpenSubKey("上海秦奋网络科技有限公司") ?? root.CreateSubKey("上海秦奋网络科技有限公司");
                if (r != null)
                {
                    return r.OpenSubKey("清风企业智能管理系统") ?? root.CreateSubKey("清风企业智能管理系统");
                }
            }
            return null;
        }

19 View Source File : RegistryHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static RegistryKey SubKey(RegistryKey key, string sub)
        {
            return key.OpenSubKey(sub, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl) ?? key.CreateSubKey(sub);
        }

19 View Source File : UpdateManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2

public void WritebackUpdate()
        {
            using (RegistryKey softwareKey = Registry.CurrentUser.CreateSubKey("Software"),
                   sdKey = softwareKey.CreateSubKey("StarDisplay"))
            {
                sdKey.SetValue("updatecfg", UpdateVersion());
            }
        }

19 View Source File : MainProgram.cs
License : MIT License
Project Creator : AlbertMN

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        [STAThread]
        static void Main(string[] args) {
            Console.WriteLine("Log location; " + logFilePath);
            CheckSettings();

            var config = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile") { FileName = logFilePath };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;

            void ActualMain() {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                //Upgrade settings
                if (Properties.Settings.Default.UpdateSettings) {
                    /* Copy old setting-files in case the Evidence type and Evidence Hash has changed (which it does sometimes) - easier than creating a whole new settings system */
                    try {
                        Configuration accConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
                        string currentFolder = new DirectoryInfo(accConfiguration.FilePath).Parent.Parent.FullName;
                        string[] directories = Directory.GetDirectories(new DirectoryInfo(currentFolder).Parent.FullName);

                        foreach (string dir in directories) {
                            if (dir != currentFolder.ToString()) {
                                var directoriesInDir = Directory.GetDirectories(dir);
                                foreach (string childDir in directoriesInDir) {
                                    string checkPath = Path.Combine(currentFolder, Path.GetFileName(childDir));
                                    if (!Directory.Exists(checkPath)) {
                                        string checkFile = Path.Combine(childDir, "user.config");
                                        if (File.Exists(checkFile)) {
                                            bool xmlHasError = false;
                                            try {
                                                XmlDoreplacedent xml = new XmlDoreplacedent();
                                                xml.Load(checkFile);

                                                xml.Validate(null);
                                            } catch {
                                                xmlHasError = true;
                                                DoDebug("XML doreplacedent validation failed (is invalid): " + checkFile);
                                            }

                                            if (!xmlHasError) {
                                                Directory.CreateDirectory(checkPath);
                                                File.Copy(checkFile, Path.Combine(checkPath, "user.config"), true);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        Console.WriteLine("Error getting settings from older versions of ACC; " + e.Message);
                    }
                    /* End "copy settings" */

                    try {
                        Properties.Settings.Default.Upgrade();
                        Properties.Settings.Default.UpdateSettings = false;
                        Properties.Settings.Default.Save();
                    } catch {
                        DoDebug("Failed to upgrade from old settings file.");
                    }

                    Console.WriteLine("Upgraded settings to match last version");
                }

                if (Properties.Settings.Default.LastUpdated == DateTime.MinValue) {
                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                }

                //Create action mod path
                if (!Directory.Exists(actionModsPath)) {
                    Directory.CreateDirectory(actionModsPath);
                }

                //Translator
                string tempDir = Path.Combine(currentLocation, "Translations");
                if (Directory.Exists(tempDir)) {
                    Translator.translationFolder = Path.Combine(currentLocation, "Translations");
                    Translator.languagesArray = Translator.GetLanguages();
                } else {
                    MessageBox.Show("Missing the translations folder. Reinstall the software to fix this issue.", messageBoxreplacedle);
                }

                string lang = Properties.Settings.Default.ActiveLanguage;
                if (Array.Exists(Translator.languagesArray, element => element == lang)) {
                    DoDebug("ACC running with language \"" + lang + "\"");

                    Translator.SetLanguage(lang);
                } else {
                    DoDebug("Invalid language chosen (" + lang + ")");

                    Properties.Settings.Default.ActiveLanguage = "English";
                    Translator.SetLanguage("English");
                }
                //End translator
                sysIcon = new SysTrayIcon();

                Properties.Settings.Default.TimesOpened += 1;
                Properties.Settings.Default.Save();

                SetupDataFolder();
                if (File.Exists(logFilePath)) {
                    try {
                        File.WriteAllText(logFilePath, string.Empty);
                    } catch {
                        // Don't let this being DENIED crash the software
                        Console.WriteLine("Failed to empty the log");
                    }
                } else {
                    Console.WriteLine("Trying to create log");
                    CreateLogFile();
                }

                //Check if software already runs, if so kill this instance
                var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));
                if (otherACCs.Length > 1) {
                    //Try kill the _other_ process instead
                    foreach (Process p in otherACCs) {
                        if (p.Id != Process.GetCurrentProcess().Id) {
                            try {
                                p.Kill();
                                DoDebug("Other ACC instance was running. Killed it.");
                            } catch {
                                DoDebug("Could not kill other process of ACC; access denied");
                            }
                        }
                    }
                }

                Application.EnableVisualStyles();

                DoDebug("[ACC begun (v" + softwareVersion + ")]");

                if (Properties.Settings.Default.CheckForUpdates) {
                    if (HasInternet()) {
                        new Thread(() => {
                            new SoftwareUpdater().Check();
                        }).Start();
                    } else {
                        DoDebug("Couldn't check for new update as PC does not have access to the internet");
                    }
                }

                //On console close: hide NotifyIcon
                Application.ApplicationExit += new EventHandler(OnApplicationExit);
                handler = new ConsoleEventDelegate(ConsoleEventCallback);
                SetConsoleCtrlHandler(handler, true);

                //Create shortcut folder if doesn't exist
                if (!Directory.Exists(shortcutLocation)) {
                    Directory.CreateDirectory(shortcutLocation);
                }
                if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt"))) {
                    //Create example-file
                    try {
                        using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                            sw.WriteLine("This is an example file.");
                            sw.WriteLine("If you haven't already, make your replacedistant open this file!");
                        }
                    } catch {
                        DoDebug("Could not create or write to example file");
                    }
                }

                //Delete all old action files
                if (Directory.Exists(CheckPath())) {
                    DoDebug("Deleting all files in action folder");
                    foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension)) {
                        int timeout = 0;

                        if (File.Exists(file)) {
                            while (ActionChecker.FileInUse(file) && timeout < 5) {
                                timeout++;
                                Thread.Sleep(500);
                            }
                            if (timeout >= 5) {
                                DoDebug("Failed to delete file at " + file + " as file appears to be in use (and has been for 2.5 seconds)");
                            } else {
                                try {
                                    File.Delete(file);
                                } catch (Exception e) {
                                    DoDebug("Failed to delete file at " + file + "; " + e.Message);
                                }
                            }
                        }
                    }
                    DoDebug("Old action files removed - moving on...");
                }

                //SetupListener();
                watcher = new FileSystemWatcher() {
                    Path = CheckPath(),
                    NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                        | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                    Filter = "*." + Properties.Settings.Default.ActionFileExtension,
                    EnableRaisingEvents = true
                };
                watcher.Changed += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Created += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Renamed += new RenamedEventHandler(new ActionChecker().FileFound);
                watcher.Deleted += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Error += delegate { DoDebug("Something wen't wrong"); };

                DoDebug("\n[" + messageBoxreplacedle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");

                sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon_light;

                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                if (Registry.GetValue(key.Name + @"\replacedistantComputerControl", "FirstTime", null) == null) {
                    SetStartup(true);

                    key.CreateSubKey("replacedistantComputerControl");
                    key = key.OpenSubKey("replacedistantComputerControl", true);
                    key.SetValue("FirstTime", false);

                    ShowGettingStarted();

                    DoDebug("Starting setup guide (first time opening ACC - wuhu!)");
                } else {
                    if (!Properties.Settings.Default.HasCompletedTutorial) {
                        ShowGettingStarted();
                        DoDebug("Didn't finish setup guide last time, opening again");
                    }
                }
                SetRegKey("ActionFolder", CheckPath());
                SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);

                testActionWindow = new TestActionWindow();

                //If newly updated
                if (Properties.Settings.Default.LastKnownVersion != softwareVersion) {
                    //Up(or down)-grade, display version notes
                    DoDebug("ACC has been updated");

                    if (Properties.Settings.Default.LastKnownVersion != "" && new System.Version(Properties.Settings.Default.LastKnownVersion) < new System.Version("1.4.3")) {
                        //Had issues before; fixed now
                        DoDebug("Upgraded to 1.4.3, fixed startup - now starting with Windows");

                        try {
                            RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                            rk.DeleteValue(appName, false);
                        } catch {
                            DoDebug("Failed to remove old start with win run");
                        }

                        SetStartup(true);
                    } else {
                        if (ACCStartsWithWindows()) {
                            SetStartup(true);
                        }
                    }

                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                    if (gettingStarted != null) {
                        DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing");
                        aboutVersionAwaiting = true;
                    } else {
                        Properties.Settings.Default.LastKnownVersion = softwareVersion;
                        new NewVersion().Show();
                    }
                    Properties.Settings.Default.Save();
                }

                //Check if software starts with Windows
                if (!ACCStartsWithWindows())
                    sysIcon.AddOpenOnStartupMenu();

                /* 'Evalufied' user feedback implementation */
                if ((DateTime.Now - Properties.Settings.Default.LastUpdated).TotalDays >= 7 && Properties.Settings.Default.TimesOpened >= 7
                    && gettingStarted == null
                    && !Properties.Settings.Default.HasPromptedFeedback) {
                    //User has had the software/update for at least 7 days, and has opened the software more than 7 times - time to ask for feedback
                    //(also the "getting started" window is not showing)
                    if (HasInternet()) {
                        try {
                            WebRequest request = WebRequest.Create("https://evalufied.dk/");
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            if (response == null || response.StatusCode != HttpStatusCode.OK) {
                                DoDebug("'Evalufied' is down - won't show faulty feedback window");
                            } else {
                                DoDebug("Showing 'User Feedback' window");
                                Properties.Settings.Default.HasPromptedFeedback = true;
                                Properties.Settings.Default.Save();
                                new UserFeedback().Show();
                            }
                        } catch {
                            DoDebug("Failed to check for 'Evalufied'-availability");
                        }
                    } else {
                        DoDebug("No internet connection, not showing user feedback window");
                    }
                }

                //Action mods implementation
                ActionMods.CheckMods();
                TaskSchedulerSetup();

                hreplacedtarted = true;
                SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep

                Application.Run();
            }

            if (sentryToken != "super_secret") {
                //Tracking issues with Sentry.IO - not forked from GitHub (official version)
                bool sentryOK = false;
                try {
                    if (Properties.Settings.Default.UID != "") {
                        Properties.Settings.Default.UID = Guid.NewGuid().ToString();
                        Properties.Settings.Default.Save();
                    }

                    if (Properties.Settings.Default.UID != "") {
                        SentrySdk.ConfigureScope(scope => {
                            scope.User = new Sentry.Protocol.User {
                                Id = Properties.Settings.Default.UID
                            };
                        });
                    }

                    using (SentrySdk.Init(sentryToken)) {
                        sentryOK = true;
                    }
                } catch {
                    //Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running
                    DoDebug("Sentry initiation failed");
                    ActualMain();
                }

                if (sentryOK) {
                    try {
                        using (SentrySdk.Init(sentryToken)) {
                            DoDebug("Sentry initiated");
                            ActualMain();
                        }
                    } catch {
                        ActualMain();
                    }
                }
            } else {
                //Code is (most likely) forked - skip issue tracking
                ActualMain();
            }
        }

19 View Source File : MainProgram.cs
License : MIT License
Project Creator : AlbertMN

public static void SetRegKey(string theKey, string setTo) {
            if (setTo != null) {
                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                if (Registry.GetValue(key.Name + "\\replacedistantComputerControl", theKey, null) == null) {
                    key.CreateSubKey("replacedistantComputerControl");
                }
                key = key.OpenSubKey("replacedistantComputerControl", true);
                key.SetValue(theKey, setTo);
            } else {
                DoDebug("Invalid value (is null)");
            }
        }

19 View Source File : AutoStarter.cs
License : MIT License
Project Creator : AlexanderPro

public static void SetAutoStartByRegister(string keyName, string replacedemblyLocation)
        {
            using (var key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION))
            {
                key.SetValue(keyName, replacedemblyLocation);
            }
        }

19 View Source File : AutoStarter.cs
License : MIT License
Project Creator : AlexanderPro

public static void UnsetAutoStartByRegister(string keyName)
        {
            using (var key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION))
            {
                key.DeleteValue(keyName);
            }
        }

19 View Source File : StartupManager.cs
License : MIT License
Project Creator : AlexGyver

private void CreateRegistryRun() {
      RegistryKey key = Registry.CurrentUser.CreateSubKey(REGISTRY_RUN);     
      key.SetValue("OpenHardwareMonitor", Application.ExecutablePath);
    }

19 View Source File : StartupManager.cs
License : MIT License
Project Creator : AlexGyver

private void DeleteRegistryRun() {
      RegistryKey key = Registry.CurrentUser.CreateSubKey(REGISTRY_RUN);
      key.DeleteValue("OpenHardwareMonitor");
    }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : Alois-xx

private static void RegisterAsEarlyStartedServiceAndAutoLogger()
        {
            ImportAutoLoggerFile();

            string serviceKeyBase = @"SYSTEM\CurrentControlSet\Services";
            string serviceKeyName =  serviceKeyBase + "\\" + ServiceName;
            var key = Registry.LocalMachine.OpenSubKey(serviceKeyName, true);
            if( key == null )
            {
                key = Registry.LocalMachine.OpenSubKey(serviceKeyBase, true);
                key = key.CreateSubKey(ServiceName);
            }

            // start service as early as possible 
            // but we still loose some events since all services are started concurrently after the servicemain was entered
            key.SetValue("Group", "Video", RegistryValueKind.String);
        }

19 View Source File : ConfigService.cs
License : Apache License 2.0
Project Creator : AmpScm

public void SaveConfig(AnkhConfig config)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            lock (_lock)
            {
                AnkhConfig defaultConfig = new AnkhConfig();
                SetDefaultsFromRegistry(defaultConfig);

                using (RegistryKey reg = OpenHKCUKey("Configuration"))
                {
                    PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(defaultConfig);
                    foreach (PropertyDescriptor pd in pdc)
                    {
                        object value = pd.GetValue(config);

                        // Set the value only if it is already set previously, or if it's different from the default
                        if (!pd.ShouldSerializeValue(config) && !pd.ShouldSerializeValue(defaultConfig))
                        {
                            reg.DeleteValue(pd.Name, false);
                        }
                        else
                        {
                            if (value.GetType() == typeof(List<ExtToolDefinition>))
                            {
                                List<ExtToolDefinition> myExtToolList = value as List<ExtToolDefinition>;
                                reg.CreateSubKey(pd.Name);
                                RegistryKey extToolReg = OpenHKCUKey("Configuration");
                                extToolReg = extToolReg.OpenSubKey(pd.Name, true);

                                if (extToolReg != null)
                                {
                                    foreach (string extToolDef in extToolReg.GetValueNames())
                                    {
                                        extToolReg.DeleteValue(extToolDef, false);
                                    }

                                    foreach (ExtToolDefinition extTool in myExtToolList)
                                    {
                                        extToolReg.SetValue(extTool.extension, extTool.exePath);
                                    }
                                }
                            }
                            else
                            {
                                reg.SetValue(pd.Name, pd.Converter.ConvertToInvariantString(value));
                            }
                        }
                    }
                }
            }
        }

19 View Source File : MigrationService.cs
License : Apache License 2.0
Project Creator : AmpScm

public void MaybeMigrate()
		{
			IAnkhPackage pkg = GetService<IAnkhPackage>();
			IAnkhCommandService cs = GetService<IAnkhCommandService>();

			if (pkg == null || cs == null)
				return;

			using (RegistryKey rkRoot = pkg.UserRegistryRoot)
			using (RegistryKey ankhMigration = rkRoot.CreateSubKey("AnkhSVN-Trigger"))
			{
				int migrateFrom = 0;
				object value = ankhMigration.GetValue(MigrateId, migrateFrom);

				if (value is int)
					migrateFrom = (int)value;
				else
					ankhMigration.DeleteValue(MigrateId, false);

				if (migrateFrom < 0)
					migrateFrom = 0;

				if (migrateFrom >= AnkhId.MigrateVersion)
					return; // Nothing to do

				try
				{
					if (cs.DirectlyExecCommand(AnkhCommand.MigrateSettings).Success)
					{
						ankhMigration.SetValue(MigrateId, AnkhId.MigrateVersion);
					}
				}
				catch
				{ /* NOP: Don't fail here... ever! */}
			}
		}

19 View Source File : SettingsKey.cs
License : Apache License 2.0
Project Creator : AmpScm

public SettingsKey GetSubKey(string strName)
        {
            return new SettingsKey(m_Key.CreateSubKey(strName));
        }

19 View Source File : SvnProxyEditor.cs
License : Apache License 2.0
Project Creator : AmpScm

private void okButton_Click(object sender, EventArgs e)
        {
            if (proxyEnabled.Checked)
            {
                using (RegistryKey rk = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Tigris.org\\Subversion\\Servers\\Global"))
                {
                    rk.SetValue(SvnConfigNames.HttpProxyHost, hostBox.Text.Trim());
                    rk.SetValue(SvnConfigNames.HttpProxyPort, portBox.Text.Trim());
                    rk.SetValue(SvnConfigNames.HttpProxyUserName, usernameBox.Text.Trim());
                    rk.SetValue(SvnConfigNames.HttpProxyPreplacedword, preplacedwordBox.Text);
                    rk.SetValue(SvnConfigNames.HttpProxyExceptions, NormalizeExceptionText(exceptionsBox.Text, false));
                }
            }
            else if (_wasEnabled)
            {
                using (RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Tigris.org\\Subversion\\Servers\\Global", true))
                {
                    rk.DeleteValue(SvnConfigNames.HttpProxyHost);
                    rk.DeleteValue(SvnConfigNames.HttpProxyPort);
                    rk.DeleteValue(SvnConfigNames.HttpProxyUserName);
                    rk.DeleteValue(SvnConfigNames.HttpProxyPreplacedword);
                    rk.DeleteValue(SvnConfigNames.HttpProxyExceptions);
                }
            }
            Context.GetService<ISvnClientPool>().FlushAllClients();
        }

19 View Source File : SvnProxyEditor.cs
License : Apache License 2.0
Project Creator : AmpScm

protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            using (RegistryKey rk = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Tigris.org\\Subversion\\Servers\\Global"))
            {
                string host = rk.GetValue(SvnConfigNames.HttpProxyHost) as string ?? "";
                string port = rk.GetValue(SvnConfigNames.HttpProxyPort) as string ?? "8080";
                string username = rk.GetValue(SvnConfigNames.HttpProxyUserName) as string ?? "";
                string preplacedword = rk.GetValue(SvnConfigNames.HttpProxyPreplacedword) as string ?? "";
                string exception = rk.GetValue(SvnConfigNames.HttpProxyExceptions) as string ?? "";

                hostBox.Text = host;

                ushort p;
                if (ushort.TryParse(port.Trim(), out p))
                    portBox.Text = p.ToString();

                usernameBox.Text = username;
                preplacedwordBox.Text = preplacedword;
                exceptionsBox.Text = NormalizeExceptionText(exception, true);

                proxyEnabled.Checked = _wasEnabled = !string.IsNullOrEmpty(host);
            }
        }

19 View Source File : RegistryExtensions.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

public static RegistryKey CreateSubKey(string fullName, RegistryView view)
        {
            RegistryHive hive = GetRegistryHive(fullName);
            string path = GetRegistryName(fullName);
            RegistryKey key = RegistryKey.OpenBaseKey(hive, view);
            key = key.CreateSubKey(path);
            return key;
        }

19 View Source File : RegistryKey.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

internal void Import(VariableCollection variables)
        {
            if (!string.IsNullOrEmpty(Name))
            {
                Microsoft.Win32.RegistryKey rootKey = Microsoft.Win32.RegistryKey.OpenBaseKey(RegistryHive, RegistryView);
                Microsoft.Win32.RegistryKey key = rootKey.OpenSubKey(Name);
                if (key == null)
                {
                    rootKey.CreateSubKey(Name);
                }
            }
            Keys.Import(variables);
            Values.Import(variables);
        }

19 View Source File : RegistryThemeHelper.cs
License : Apache License 2.0
Project Creator : angelwzr

public static void SetWindowsTheme(UITheme theme)
        {
            using var key = Registry.CurrentUser.CreateSubKey(RegistryKeyPathTheme);

            switch (theme)
            {
                case UITheme.Light:
                    key.SetValue(RegSysMode, "1", RegistryValueKind.DWord);
                    key.SetValue(RegColPMode, "0", RegistryValueKind.DWord);
                    break;

                case UITheme.Dark:
                    key.SetValue(RegSysMode, "0", RegistryValueKind.DWord);
                    break;
            }

            key.Close();
        }

19 View Source File : RegistryThemeHelper.cs
License : Apache License 2.0
Project Creator : angelwzr

public static void SetAppsTheme(UITheme theme)
        {
            using var key = Registry.CurrentUser.CreateSubKey(RegistryKeyPathTheme);

            switch (theme)
            {
                case UITheme.Light:
                    key.SetValue(RegAppMode, "1", RegistryValueKind.DWord);
                    break;

                case UITheme.Dark:
                    key.SetValue(RegAppMode, "0", RegistryValueKind.DWord);
                    break;
            }

            key.Close();
        }

19 View Source File : RegistryThemeHelper.cs
License : Apache License 2.0
Project Creator : angelwzr

public static void ResetTheme()
        {
            using var key = Registry.CurrentUser.CreateSubKey(RegistryKeyPathTheme);

            key.SetValue(RegSysMode, "1", RegistryValueKind.DWord);
            key.SetValue(RegAppMode, "1", RegistryValueKind.DWord);
            key.SetValue(RegColPMode, "0", RegistryValueKind.DWord);
            key.Close();
        }

19 View Source File : WebBrowserHelper.cs
License : MIT License
Project Creator : 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 View Source File : FileExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

private static void replacedociateExtensionWindows(string extension, string formatDescription)
        {
            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
            {
                string iconPath = Path.Combine(Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName), "Icons");
                string iconFile;

                if (File.Exists(Path.Combine(iconPath, extension + ".ico")))
                {
                    iconFile = Path.Combine(iconPath, extension + ".ico");
                }
                else
                {
                    iconFile = Path.Combine(iconPath, "tree.ico");
                }

                RegistryKey extensionKey = Registry.ClreplacedesRoot.OpenSubKey("." + extension, true);

                if (extensionKey != null)
                {
                    Registry.ClreplacedesRoot.DeleteSubKeyTree("." + extension);
                }

                extensionKey = Registry.ClreplacedesRoot.CreateSubKey("." + extension);
                extensionKey.SetValue(null, "TreeViewer." + extension, RegistryValueKind.String);

                RegistryKey commandKey = Registry.ClreplacedesRoot.OpenSubKey("TreeViewer." + extension, true);

                if (commandKey != null)
                {
                    Registry.ClreplacedesRoot.DeleteSubKeyTree("TreeViewer." + extension);
                }

                commandKey = Registry.ClreplacedesRoot.CreateSubKey("TreeViewer." + extension);
                commandKey.SetValue(null, formatDescription, RegistryValueKind.String);

                commandKey.CreateSubKey("DefaultIcon").SetValue(null, "\"" + iconFile + "\"");

                RegistryKey shellKey = commandKey.CreateSubKey("shell");
                shellKey.SetValue(null, "Open", RegistryValueKind.String);

                shellKey.CreateSubKey("Open").CreateSubKey("command").SetValue(null, "\"" + System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName + "\" \"%1\"", RegistryValueKind.String);
            }
        }

19 View Source File : Registry.cs
License : GNU General Public License v3.0
Project Creator : Artentus

public static string RegisterHandler(string appName, string component, int version, string appPath, string description, string iconPath)
        {
            if (string.IsNullOrEmpty(component)) throw new ArgumentNullException(nameof(component));

            bool changed = false;

            string progId = (version < 0) ? string.Join(".", appName, component) : string.Join(".", appName, component, version);
            RegistryKey? handlerKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(Path.Combine(@"Software\Clreplacedes", progId));

            if (handlerKey is not null)
            {
                if (!string.IsNullOrEmpty(description))
                {
                    if (!string.Equals(handlerKey.GetString(null), description, StringComparison.InvariantCulture))
                    {
                        handlerKey.SetString(null, description);
                        changed = true;
                    }
                    if (!string.Equals(handlerKey.GetString("FriendlyTypeName"), description, StringComparison.InvariantCulture))
                    {
                        handlerKey.SetString("FriendlyTypeName", description);
                        changed = true;
                    }
                }

                if (!string.IsNullOrEmpty(iconPath))
                {
                    RegistryKey? iconKey = handlerKey.CreateSubKey("DefaultIcon");
                    if ((iconKey is not null) && !string.Equals(iconKey.GetString(null), iconPath, StringComparison.InvariantCulture))
                    {
                        iconKey.SetString(null, iconPath);
                        changed = true;
                    }
                }

                string command = $"{appPath} \"%1\"";
                RegistryKey? openKey = handlerKey.CreateSubKey(@"shell\open\command");
                if ((openKey is not null) && !string.Equals(openKey.GetString(null), command, StringComparison.InvariantCulture))
                {
                    openKey.SetValue(null, command);
                    changed = true;
                }
            }

            if (changed) Shell32.ChangeNotify(ChangeNotifyEventId.replacedociationChanged, ChangeNotifyFlags.IdList);

            return progId;
        }

19 View Source File : Registry.cs
License : GNU General Public License v3.0
Project Creator : Artentus

public static void RegisterFileType(string extension, string handlerName, string mimeType, PercievedFileType percievedType)
        {
            if (string.IsNullOrEmpty(extension)) throw new ArgumentNullException(nameof(extension));
            if (string.IsNullOrEmpty(handlerName)) throw new ArgumentNullException(nameof(handlerName));

            if (!extension.StartsWith(".")) extension = "." + extension;

            bool changed = false;

            RegistryKey? extensionKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(Path.Combine(@"Software\Clreplacedes", extension));

            if (extensionKey is not null)
            {
                extensionKey.SetString(null, handlerName);

                if (!string.IsNullOrEmpty(mimeType) && !string.Equals(extensionKey.GetString("Content Type"), mimeType, StringComparison.InvariantCulture))
                {
                    extensionKey.SetString("Content Type", mimeType);
                    changed = true;
                }

                if ((percievedType != PercievedFileType.None) && !string.Equals(extensionKey.GetString("PerceivedType"), percievedType.ToString("g"), StringComparison.InvariantCulture))
                {
                    extensionKey.SetString("PerceivedType", percievedType.ToString("g"));
                    changed = true;
                }

                RegistryKey? openWithKey = extensionKey.CreateSubKey("OpenWithProgids");
                if (openWithKey is not null)
                {
                    if (!openWithKey.ContainsName(handlerName))
                    {
                        openWithKey.AddName(handlerName);
                        changed = true;
                    }
                }
            }

            if (changed) Shell32.ChangeNotify(ChangeNotifyEventId.replacedociationChanged, ChangeNotifyFlags.IdList);
        }

19 View Source File : LocalServer.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative

private static void RegisterObjects()
        {
            if (!IsAdministrator)
            {
                ElevateSelf("/register");
                return;
            }
            //
            // If reached here, we're running elevated
            //

            TraceLogger TL = new TraceLogger("RemoteClientServer")
            {
                Enabled = true
            };

            replacedembly replacedy = replacedembly.GetExecutingreplacedembly();
            Attribute attr = Attribute.GetCustomAttribute(replacedy, typeof(replacedemblyreplacedleAttribute));
            string replacedyreplacedle = ((replacedemblyreplacedleAttribute)attr).replacedle;
            attr = Attribute.GetCustomAttribute(replacedy, typeof(replacedemblyDescriptionAttribute));
            string replacedyDescription = ((replacedemblyDescriptionAttribute)attr).Description;

            //
            // Local server's DCOM/AppID information
            //
            try
            {
                //
                // HKCR\APPID\appid
                //
                using (RegistryKey key = Registry.ClreplacedesRoot.CreateSubKey("APPID\\" + s_appId))
                {
                    key.SetValue(null, replacedyDescription);
                    key.SetValue("AppID", s_appId);
                    key.SetValue("AuthenticationLevel", 1, RegistryValueKind.DWord);
                }
                //
                // HKCR\APPID\exename.ext
                //
                using (RegistryKey key = Registry.ClreplacedesRoot.CreateSubKey(string.Format("APPID\\{0}", Application.ExecutablePath.Substring(Application.ExecutablePath.LastIndexOf('\\') + 1))))
                {
                    key.SetValue("AppID", s_appId);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while registering the server:\n" + ex.ToString(),
                        "Remote Local Server", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            finally
            {
            }

            TL.LogMessage("RegisterObjects", "Registering types");

            //
            // For each of the driver replacedemblies
            //
            foreach (Type type in s_ComObjectTypes)
            {
                TL.LogMessage("RegisterObjects", string.Format("Processing type: {0}, is a COM object: {1}", type.FullName, type.IsCOMObject));
                bool bFail = false;
                try
                {
                    //
                    // HKCR\CLSID\clsid
                    //
                    string clsid = Marshal.GenerateGuidForType(type).ToString("B");
                    string progid = Marshal.GenerateProgIdForType(type);
                    //PWGS Generate device type from the Clreplaced name
                    string deviceType = type.Name;

                    using (RegistryKey key = Registry.ClreplacedesRoot.CreateSubKey(string.Format("CLSID\\{0}", clsid)))
                    {
                        key.SetValue(null, progid);						// Could be replacedyreplacedle/Desc??, but .NET components show ProgId here
                        key.SetValue("AppId", s_appId);
                        using (RegistryKey key2 = key.CreateSubKey("Implemented Categories"))
                        {
                            key2.CreateSubKey("{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}");
                        }
                        using (RegistryKey key2 = key.CreateSubKey("ProgId"))
                        {
                            key2.SetValue(null, progid);
                        }
                        key.CreateSubKey("Programmable");
                        using (RegistryKey key2 = key.CreateSubKey("LocalServer32"))
                        {
                            key2.SetValue(null, Application.ExecutablePath);
                        }
                    }

                    //
                    // HKCR\APPID\clsid  For TheSkyX DCOM
                    //
                    using (RegistryKey key = Registry.ClreplacedesRoot.CreateSubKey("APPID\\" + clsid))
                    {
                        key.SetValue(null, replacedyDescription);
                        key.SetValue("AppID", clsid);
                        key.SetValue("AuthenticationLevel", 1, RegistryValueKind.DWord);
                    }

                    //
                    // HKCR\CLSID\progid
                    //
                    using (RegistryKey key = Registry.ClreplacedesRoot.CreateSubKey(progid))
                    {
                        key.SetValue(null, replacedyreplacedle);
                        using (RegistryKey key2 = key.CreateSubKey("CLSID"))
                        {
                            key2.SetValue(null, clsid);
                        }
                    }
                    //
                    // ASCOM 
                    //
                    replacedy = type.replacedembly;

                    // Pull the display name from the ServedClreplacedName attribute.
                    attr = Attribute.GetCustomAttribute(type, typeof(ServedClreplacedNameAttribute)); //PWGS Changed to search type for attribute rather than replacedembly
                    string chooserName = ((ServedClreplacedNameAttribute)attr).DisplayName ?? "MultiServer";
                    using (var P = new ASCOM.Utilities.Profile())
                    {
                        P.DeviceType = deviceType;
                        P.Register(progid, chooserName);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error while registering the server:\n" + ex.ToString(), "Remote Local Server", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    bFail = true;
                }
                finally
                {
                }
                if (bFail) break;
            }
        }

19 View Source File : Configuration.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative

public T GetValue<T>(string KeyName, string SubKey, T DefaultValue)
        {
            if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Getting {0} value '{1}' in subkey '{2}', default: '{3}'", typeof(T).Name, KeyName, SubKey, DefaultValue.ToString()));

            if (typeof(T) == typeof(bool))
            {
                string registryValue;
                if (SubKey == "")
                {
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly");
                    registryValue = (string)baseRegistryKey.GetValue(KeyName);
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }
                else
                {
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it...");
                    registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName);
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }

                if (registryValue == null)
                {
                    SetValueInvariant<T>(KeyName, SubKey, DefaultValue);
                    bool defaultValue = Convert.ToBoolean(DefaultValue);
                    registryValue = defaultValue.ToString(CultureInfo.InvariantCulture);
                }

                bool RetVal = Convert.ToBoolean(registryValue, CultureInfo.InvariantCulture);
                if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString()));
                return (T)((object)RetVal);
            }

            if (typeof(T) == typeof(string))
            {
                string RetVal;
                if (SubKey == "")
                {
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly");
                    RetVal = (string)baseRegistryKey.GetValue(KeyName);
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + RetVal);
                }
                else
                {
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it...");
                    RetVal = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName);
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + RetVal);
                }

                if (RetVal == null)
                {
                    SetValue<T>(KeyName, SubKey, DefaultValue);
                    RetVal = DefaultValue.ToString();
                }
                if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString()));
                return (T)((object)RetVal);
            }

            if (typeof(T) == typeof(decimal))
            {
                string registryValue;
                if (SubKey == "")
                {
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly");
                    registryValue = (string)baseRegistryKey.GetValue(KeyName);
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }
                else
                {
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it...");
                    registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName);
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }

                if (registryValue == null)
                {
                    SetValueInvariant<T>(KeyName, SubKey, DefaultValue);
                    decimal defaultValue = Convert.ToDecimal(DefaultValue);
                    registryValue = defaultValue.ToString(CultureInfo.InvariantCulture);
                }

                decimal RetVal = Convert.ToDecimal(registryValue, CultureInfo.InvariantCulture);
                if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString()));
                return (T)((object)RetVal);
            }

            if (typeof(T) == typeof(DateTime))
            {
                string registryValue;
                if (SubKey == "")
                {
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly");
                    registryValue = (string)baseRegistryKey.GetValue(KeyName);
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }
                else
                {
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it...");
                    registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName);
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }

                if (registryValue == null)
                {
                    SetValueInvariant<T>(KeyName, SubKey, DefaultValue);
                    return DefaultValue;
                }

                if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue DateTime", $"String value prior to Convert: {registryValue}");

                if (DateTime.TryParse(registryValue, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTime RetVal))
                {
                    // The string parsed OK so return the parsed value;
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue DateTime", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString()));
                    return (T)((object)RetVal);
                }
                else // If the string fails to parse, overwrite with the default value and return this
                {
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue DateTime", $"Failed to parse registry value, persisting and returning the default value: {DefaultValue}");
                    SetValueInvariant<T>(KeyName, SubKey, DefaultValue);
                    return DefaultValue;
                }
            }

            if ((typeof(T) == typeof(Int32)) | (typeof(T) == typeof(int)))
            {
                string registryValue;
                if (SubKey == "")
                {
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly");
                    registryValue = (string)baseRegistryKey.GetValue(KeyName);
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }
                else
                {
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it...");
                    registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName);
                    if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }

                if (registryValue == null)
                {
                    SetValueInvariant<T>(KeyName, SubKey, DefaultValue);
                    int defaultValue = Convert.ToInt32(DefaultValue);
                    registryValue = defaultValue.ToString(CultureInfo.InvariantCulture);
                }

                int RetVal = Convert.ToInt32(registryValue, CultureInfo.InvariantCulture);
                if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString()));
                return (T)((object)RetVal);
            }

            throw new DriverException("GetValue: Unknown type: " + typeof(T).Name);
        }

19 View Source File : Configuration.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative

public void SetValue<T>(string KeyName, string SubKey, T Value)
        {
            if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "SetValue", string.Format("Setting {0} value '{1}' in subkey '{2}' to: '{3}'", typeof(T).Name, KeyName, SubKey, Value.ToString()));

            if (SubKey == "") baseRegistryKey.SetValue(KeyName, Value.ToString());
            else baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, Value.ToString());
        }

19 View Source File : Configuration.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative

public void SetValueInvariant<T>(string KeyName, string SubKey, T Value)
        {
            if (LOG_CONFIGURATION_CALLS) ServerForm.LogMessage(0, 0, 0, "SetValue DateTime", string.Format("Setting {0} value '{1}' in subkey '{2}' to: '{3}'", typeof(T).Name, KeyName, SubKey, Value.ToString()));

            if ((typeof(T) == typeof(Int32)) | (typeof(T) == typeof(int)))
            {
                int intValue = Convert.ToInt32(Value);
                if (SubKey == "") baseRegistryKey.SetValue(KeyName, intValue.ToString(CultureInfo.InvariantCulture));
                else baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, intValue.ToString(CultureInfo.InvariantCulture));
                return;
            }

            if (typeof(T) == typeof(bool))
            {
                bool boolValue = Convert.ToBoolean(Value);
                if (SubKey == "") baseRegistryKey.SetValue(KeyName, boolValue.ToString(CultureInfo.InvariantCulture));
                else baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, boolValue.ToString(CultureInfo.InvariantCulture));
                return;
            }

            if (typeof(T) == typeof(decimal))
            {
                decimal decimalValue = Convert.ToDecimal(Value);
                if (SubKey == "") baseRegistryKey.SetValue(KeyName, decimalValue.ToString(CultureInfo.InvariantCulture));
                else baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, decimalValue.ToString(CultureInfo.InvariantCulture));
                return;
            }

            if (typeof(T) == typeof(DateTime))
            {
                DateTime dateTimeValue = Convert.ToDateTime(Value);
                if (SubKey == "") baseRegistryKey.SetValue(KeyName, dateTimeValue.ToString("HH:mm:ss", CultureInfo.InvariantCulture));
                else baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, dateTimeValue.ToString("HH:mm:ss", CultureInfo.InvariantCulture));
                return;
            }

            throw new DriverException("SetValueInvariant: Unknown type: " + typeof(T).Name);
        }

19 View Source File : Configuration.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative

public T GetValue<T>(string KeyName, string SubKey, T DefaultValue)
        {
            if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Getting {0} value '{1}' in subkey '{2}', default: '{3}'", typeof(T).Name, KeyName, SubKey, DefaultValue.ToString()));
            if (typeof(T) == typeof(bool))
            {
                string registryValue = "RegistryTestValue1";
                if (SubKey == "")
                {
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly");
                    registryValue = (string)baseRegistryKey.GetValue(KeyName);
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }
                else
                {
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it...");
                    registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName);
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }

                if (registryValue == null)
                {
                    SetValue<T>(KeyName, SubKey, DefaultValue);
                    registryValue = DefaultValue.ToString();
                }
                bool RetVal = Convert.ToBoolean(registryValue, CultureInfo.InvariantCulture);
                if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString()));
                return (T)((object)RetVal);
            }

            if (typeof(T) == typeof(string))
            {
                //string RetVal = (string)baseRegistryKey.CreateSubKey(SubKey, true).GetValue(KeyName);
                string RetVal = "RegistryTestValue2";
                if (SubKey == "")
                {
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly");
                    RetVal = (string)baseRegistryKey.GetValue(KeyName);
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + RetVal);
                }
                else
                {
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it...");
                    RetVal = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName);
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + RetVal);
                }

                if (RetVal == null)
                {
                    SetValue<T>(KeyName, SubKey, DefaultValue);
                    RetVal = DefaultValue.ToString();
                }
                if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString()));
                return (T)((object)RetVal);
            }

            if (typeof(T) == typeof(decimal))
            {
                string registryValue = "RegistryTestValue2";
                if (SubKey == "")
                {
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly");
                    registryValue = (string)baseRegistryKey.GetValue(KeyName);
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }
                else
                {
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it...");
                    registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName);
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }

                if (registryValue == null)
                {
                    SetValue<T>(KeyName, SubKey, DefaultValue);
                    registryValue = DefaultValue.ToString();
                }
                decimal RetVal = Convert.ToDecimal(registryValue, CultureInfo.InvariantCulture);
                if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString()));
                return (T)((object)RetVal);
            }

            if (typeof(T) == typeof(Int32))
            {
                string registryValue = "RegistryTestValue3";
                if (SubKey == "")
                {
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey is empty so getting value directly");
                    registryValue = (string)baseRegistryKey.GetValue(KeyName);
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }
                else
                {
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "SubKey has a value so using it...");
                    registryValue = (string)baseRegistryKey.CreateSubKey(SubKey).GetValue(KeyName);
                    if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", "Value retrieved OK: " + registryValue);
                }

                if (registryValue == null)
                {
                    SetValue<T>(KeyName, SubKey, DefaultValue);
                    registryValue = DefaultValue.ToString();
                }
                Int32 RetVal = Convert.ToInt32(registryValue, CultureInfo.InvariantCulture);
                if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "GetValue", string.Format("Retrieved {0} = {1}", KeyName, RetVal.ToString()));
                return (T)((object)RetVal);
            }

            throw new DriverException("GetValue: Unknown type: " + typeof(T).Name);
        }

19 View Source File : Configuration.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative

public void SetValue<T>(string KeyName, string SubKey, T Value)
        {
            if (ServerForm.DebugTraceState) ServerForm.LogMessage(0, 0, 0, "SetValue", string.Format("Setting {0} value '{1}' in subkey '{2}' to: '{3}'", typeof(T).Name, KeyName, SubKey, Value.ToString()));

            if (SubKey == "") baseRegistryKey.SetValue(KeyName, Value.ToString());
            else baseRegistryKey.CreateSubKey(SubKey).SetValue(KeyName, Value.ToString());
        }

19 View Source File : Component.cs
License : Microsoft Public License
Project Creator : atrenton

internal static void Register(Type t)
        {
            Tracer.WriteTraceMethodLine();
            if (t.FullName == Component.ProgId)
            {
                if (!IsOneNoteInstalled())
                {
                    var errorMessage =
                      "Oops... Can't register component.\r\n" + ONENOTE_APP_NOT_FOUND;
                    Utils.WinHelper.DisplayError(errorMessage);
                    return;
                }
                WritereplacedemblyInfoProperties();
                try
                {
                    Tracer.WriteDebugLine("Creating HKCR subkey: {0}", s_appId_subkey);
                    using (var k = Registry.ClreplacedesRoot.CreateSubKey(s_appId_subkey))
                    {
                        k.SetValue(null, replacedemblyInfo.Description);

                        // Use the default COM Surrogate process (dllhost.exe) to activate the DLL
                        k.SetValue("DllSurrogate", string.Empty);
                    }
                    Tracer.WriteDebugLine("Updating HKCR subkey: {0}", s_clsId_subkey);
                    using (var k = Registry.ClreplacedesRoot.OpenSubKey(s_clsId_subkey, true))
                    {
                        k.SetValue("AppID", s_appId_guid);
                        using (var defaultIcon = k.CreateSubKey("DefaultIcon"))
                        {
                            var path = replacedembly.GetExecutingreplacedembly().Location;
                            var resourceID = 0;
                            defaultIcon.SetValue(null, $"\"{path}\",{resourceID}");
                        }
                    }
                    // Register add-in for all users
                    Tracer.WriteDebugLine("Creating HKLM subkey: {0}", s_addIn_subkey);
                    using (var k = Registry.LocalMachine.CreateSubKey(s_addIn_subkey))
                    {
                        var dword = RegistryValueKind.DWord;
                        k.SetValue("CommandLineSafe", Component.CommandLineSafe, dword);
                        k.SetValue("Description", Component.Description);
                        k.SetValue("FriendlyName", Component.FriendlyName);
                        k.SetValue("LoadBehavior", Component.LoadBehavior, dword);
                    }
                }
                catch (Exception e)
                {
                    Utils.WinHelper.DisplayError("Oops... Can't register component.");
                    Utils.ExceptionHandler.HandleException(e);
                }
            }
        }

19 View Source File : FileAssociation.cs
License : GNU General Public License v3.0
Project Creator : audiamus

private static bool setKeyValue (string keyPath, string value, string name = null) {
      bool dirty = false;
      // does key exist?
      using (var key = Registry.CurrentUser.OpenSubKey (keyPath)) {
        dirty = key is null;
      }

      using (var key = Registry.CurrentUser.CreateSubKey (keyPath)) {
        if (name is null) {
          if (key.GetValue (name) as string != value) {
            key.SetValue (name, value);
            dirty = true;
          }
        } else {
          var names = key.GetValueNames ();
          if (names.Contains (name)) {
            if (key.GetValue (name) as string != value) {
              key.SetValue (name, value);
              dirty = true;
            } 
          } else { 
            key.SetValue (name, value);
            dirty = true;
          }
        }
      }

      return dirty;
    }

19 View Source File : ShellExtLib.cs
License : MIT License
Project Creator : Autodesk-Forge

public static void RegisterShellExtContextMenuHandler(Guid clsid,
        string fileType, string friendlyName)
    {
      if (clsid == Guid.Empty)
      {
        throw new ArgumentException("clsid must not be empty");
      }
      if (string.IsNullOrEmpty(fileType))
      {
        throw new ArgumentException("fileType must not be null or empty");
      }

      // If fileType starts with '.', try to read the default value of the 
      // HKCR\<File Type> key which contains the ProgID to which the file type 
      // is linked.
      if (fileType.StartsWith("."))
      {
        using (RegistryKey key = Registry.ClreplacedesRoot.OpenSubKey(fileType))
        {
          if (key != null)
          {
            // If the key exists and its default value is not empty, use 
            // the ProgID as the file type.
            string defaultVal = key.GetValue(null) as string;
            if (!string.IsNullOrEmpty(defaultVal))
            {
              fileType = defaultVal;
            }
          }
        }
      }

      // Create the key HKCR\<File Type>\shellex\ContextMenuHandlers\{<CLSID>}.
      string keyName = string.Format(@"{0}\shellex\ContextMenuHandlers\{1}",
          fileType, clsid.ToString("B"));
      using (RegistryKey key = Registry.ClreplacedesRoot.CreateSubKey(keyName))
      {
        // Set the default value of the key.
        if (key != null && !string.IsNullOrEmpty(friendlyName))
        {
          key.SetValue(null, friendlyName);
        }
      }
    }

19 View Source File : IPCAdapterRpcBuffer.cs
License : MIT License
Project Creator : automuteus

private static void RegisterProtocol()
        {
            // Literally code that only works under Windows. This isn't even included with the .NET Core 3 Linux runtime.
            // Consider handling protocol registration outside of this library.
            using (var key = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Clreplacedes\\" + UriScheme))
            {
                // Replace typeof(App) by the clreplaced that contains the Main method or any clreplaced located in the project that produces the exe.
                // or replace typeof(App).replacedembly.Location by anything that gives the full path to the exe
                var applicationLocation = Program.GetExecutablePath();

                key.SetValue("", "URL:" + FriendlyName);
                key.SetValue("URL Protocol", "");

                using (var defaultIcon = key.CreateSubKey("DefaultIcon"))
                {
                    defaultIcon.SetValue("", applicationLocation + ",1");
                }

                using (var commandKey = key.CreateSubKey(@"shell\open\command"))
                {
                    commandKey.SetValue("", "\"" + applicationLocation + "\" \"%1\"");
                }
            }
        }

19 View Source File : IPCAdapterRpcBuffer.cs
License : MIT License
Project Creator : automuteus

private static void RegisterProtocol()
        {
            // Literally code that only works under Windows. This isn't even included with the .NET Core 3 Linux runtime.
            // Consider handling protocol registration outside of this library.
            //#if _WINDOWS
            using (var key = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Clreplacedes\\" + UriScheme))
            {
                // Replace typeof(App) by the clreplaced that contains the Main method or any clreplaced located in the project that produces the exe.
                // or replace typeof(App).replacedembly.Location by anything that gives the full path to the exe
                var applicationLocation = App.GetExecutablePath();

                key.SetValue("", "URL:" + FriendlyName);
                key.SetValue("URL Protocol", "");

                using (var defaultIcon = key.CreateSubKey("DefaultIcon"))
                {
                    defaultIcon.SetValue("", applicationLocation + ",1");
                }

                using (var commandKey = key.CreateSubKey(@"shell\open\command"))
                {
                    commandKey.SetValue("", "\"" + applicationLocation + "\" \"%1\"");
                }
            }
            //#endif
        }

19 View Source File : RegistrationUtility.cs
License : MIT License
Project Creator : avarghesein

internal static void RegisterLocalServer(Type t)
        {
            GuardNullType(t, "t");  // Check the argument

            if (!ValidateActiveXServerAttribute(t)) return;

            try
            {
                // Open the CLSID key of the component.
                using (RegistryKey keyCLSID = Registry.ClreplacedesRoot.OpenSubKey(
                    @"CLSID\" + t.GUID.ToString("B"), /*writable*/true))
                {
                    // Remove the auto-generated InprocServer32 key after registration
                    // (REGASM puts it there but we are going out-of-proc).
                    keyCLSID.DeleteSubKeyTree("InprocServer32");

                    // Create "LocalServer32" under the CLSID key
                    using (RegistryKey subkey = keyCLSID.CreateSubKey("LocalServer32"))
                    {
                        subkey.SetValue("", replacedembly.GetEntryreplacedembly().Location, RegistryValueKind.String);
                    }
                }
            }
            catch (Exception eX)
            {
                System.Windows.Forms.MessageBox.Show(eX.Message);
            }
        }

19 View Source File : AyFuncFileExtRegister.cs
License : MIT License
Project Creator : 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 View Source File : AyFuncRegisterTable.cs
License : MIT License
Project Creator : ay2015

public void Write(RegistryKey root, string subkey, string name, string value)
        {
            RegistryKey aimdir = root.CreateSubKey(subkey);
            aimdir.SetValue(name, value);
        }

19 View Source File : Login.cs
License : MIT License
Project Creator : b9q

private void btnLogin_Click(object sender, EventArgs e)
        {
            dynamic result = Networking.Login(flex_username_box.Text, flex_preplacedword_box.Text);

            if (result != null)
            {
                if ((string)result.status == "failed")
                {
                    string issue = (string)result.detail;
                    string extra_information = (string)result.extra;
                    switch (issue)
                    {
                        case "connection error":
                        default:
                            unknown_error();
                            return;
                        case "no account":
                        case "wrong preplacedword":
                            MessageBox.Show("Incorrect username or preplacedword.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            flex_preplacedword_box.ResetText();
                            return;
                        case "sub invalid":
                            MessageBox.Show("Your subscription is invalid or expired.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        case "hwid mismatch":
                            MessageBox.Show("Your PC is not authorized.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        case "banned":
                            MessageBox.Show("Your account has been banned.\nReason: " + extra_information, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            security_functions.delete_self();
                            Environment.Exit(1);
                            return;
                        case "server offline":
                            MessageBox.Show($"The server is currently disabled.\nReason: {(string)result.reason}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Environment.Exit(5);
                            break;
                    }
                }
                else if ((string)result.status == "successful" && (string)result.username == flex_username_box.Text && (int)result.time_left > 0)
                {

                    if (c_utility.get_epoch_time() - (double) result.time > 30)
                    {
                        Environment.Exit(0); //prevent replay attacks
                        return;
                    }

                    if (flex_remember_me.Checked)
                    {
                        Properties.Settings.Default.username = flex_username_box.Text;
                        Properties.Settings.Default.preplacedword = flex_preplacedword_box.Text;
                        Properties.Settings.Default.Save();
                    }

                    RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);

                    key.CreateSubKey("VER$ACE");
                    key = key.OpenSubKey("VER$ACE", true);
                    key.SetValue("username", aes.encrypt_string((string)result.username));

                    MessageBox.Show($"Welcome back, {(string)result.username}!\n This build was created on [BUILD]", "VER$ACE", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    saved_info.username = flex_username_box.Text;
                    saved_info.preplacedword = flex_preplacedword_box.Text;

                    keep_open = true;
                    Forms.Main form = new Forms.Main(result);
                    form.Show();
                    Hide();
                }
                else {
                    unknown_error();
                }
            }
            else {
                unknown_error();
            }
        }

19 View Source File : UninstallEntry.cs
License : GNU General Public License v2.0
Project Creator : 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 View Source File : Install.xaml.cs
License : GNU General Public License v2.0
Project Creator : BlackTasty

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

19 View Source File : UninstallEntry.cs
License : GNU General Public License v2.0
Project Creator : 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 View Source File : WinUtils.cs
License : MIT License
Project Creator : BleuBleu

private static bool SetKeyDefaultValue(string keyPath, string value)
        {
            using (var key = Registry.CurrentUser.CreateSubKey(keyPath))
            {
                if (key.GetValue(null) as string != value)
                {
                    key.SetValue(null, value);
                    return true;
                }
            }

            return false;
        }

19 View Source File : RegistryEx.cs
License : MIT License
Project Creator : BluePointLilac

public static RegistryKey CreateSubKey(this RegistryKey key, string subKeyName, bool writable)
        {
            using(key.CreateSubKey(subKeyName))
                return key.OpenSubKey(subKeyName, writable);
        }

See More Examples