OpenSubKey() public méthode

public OpenSubKey ( string name ) : Microsoft.Win32.RegistryKey
name string
Résultat Microsoft.Win32.RegistryKey
 /// <summary>
 /// 获取注册表项的子节点,并将其添加到树形控件节点中
 /// </summary>
 /// <param name="nodes"></param>
 /// <param name="rootKey"></param>
 public void GetSubKey(TreeNodeCollection nodes, RegistryKey rootKey)
 {
     if (nodes.Count != 0) return;
     //获取项的子项名称列表
     string[] keyNames = rootKey.GetSubKeyNames();
     //遍历子项名称
     foreach (string keyName in keyNames)
     {
     try
     {
     //根据子项名称功能注册表项
     RegistryKey key = rootKey.OpenSubKey(keyName);
     //如果表项不存在,则继续遍历下一表项
     if (key == null) continue;
     //根据子项名称创建对应树形控件节点
     TreeNode TNRoot = new TreeNode(keyName);
     //将注册表项与树形控件节点绑定在一起
     TNRoot.Tag = key;
     //向树形控件中添加节点
     nodes.Add(TNRoot);
     }
     catch
     {
     //如果由于权限问题无法访问子项,则继续搜索下一子项
     continue;
     }
     }
 }
 public static string GetRegistryStringValue(RegistryKey baseKey, string strSubKey, string strValue)
 {
     object obj = null;
     string text = string.Empty;
     string result;
     try
     {
         RegistryKey registryKey = baseKey.OpenSubKey(strSubKey);
         if (registryKey == null)
         {
             result = null;
             return result;
         }
         obj = registryKey.GetValue(strValue);
         if (obj == null)
         {
             result = null;
             return result;
         }
         registryKey.Close();
         baseKey.Close();
     }
     catch (Exception ex)
     {
         text = ex.Message;
         result = null;
         return result;
     }
     result = obj.ToString();
     return result;
 }
 public void CopyFromRegistry(RegistryKey keyToSave)
 {
     if (keyToSave == null)
     {
         throw new ArgumentNullException("keyToSave");
     }
     this.ValueNames = keyToSave.GetValueNames();
     if (this.ValueNames == null)
     {
         this.ValueNames = new string[0];
     }
     this.Values = new object[this.ValueNames.Length];
     for (int i = 0; i < this.ValueNames.Length; i++)
     {
         this.Values[i] = keyToSave.GetValue(this.ValueNames[i]);
     }
     this.KeyNames = keyToSave.GetSubKeyNames();
     if (this.KeyNames == null)
     {
         this.KeyNames = new string[0];
     }
     this.Keys = new SerializableRegistryKey[this.KeyNames.Length];
     for (int j = 0; j < this.KeyNames.Length; j++)
     {
         this.Keys[j] = new SerializableRegistryKey(keyToSave.OpenSubKey(this.KeyNames[j]));
     }
 }
 public UninstallerObject(RegistryKey rootKey, string keyPath, string keyName)
 {
     using (RegistryKey hkKey = rootKey.OpenSubKey(keyPath, false))
     {
         string ApplicationName = hkKey.GetValue("DisplayName") as string;
         if (string.IsNullOrEmpty(ApplicationName))
         {
             ApplicationName = hkKey.GetValue("QuietDisplayName") as string;
         }
         if (string.IsNullOrEmpty(ApplicationName))
             ApplicationName = keyName;
         Objects[(int)UninstallerItemTypes.Application] = ApplicationName;
         Objects[(int)UninstallerItemTypes.Path] = hkKey.GetValue("InstallLocation") as string;
         Objects[(int)UninstallerItemTypes.Key] = keyName;
         Objects[(int)UninstallerItemTypes.Version] = hkKey.GetValue("DisplayVersion") as string;
         Objects[(int)UninstallerItemTypes.Publisher] = hkKey.GetValue("Publisher") as string;
         Objects[(int)UninstallerItemTypes.HelpLink] = hkKey.GetValue("HelpLink") as string;
         Objects[(int)UninstallerItemTypes.AboutLink] = hkKey.GetValue("URLInfoAbout") as string;
         ToolTipText = hkKey.GetValue("UninstallString") as string;
         Objects[(int)UninstallerItemTypes.Action] = ToolTipText;
         if (string.IsNullOrEmpty(ToolTipText))
         {
             ForegroundColor = Color.Gray;
         }
         else if (!string.IsNullOrEmpty(Path))
         {
             ForegroundColor = Color.Blue;
         }
     }
 }
        internal PackageInfo(RegistryKey key)
        {
            PackageId = Path.GetFileName(key.Name);
            DisplayName = (string)key.GetValue("DisplayName");
            PackageRootFolder = (string)key.GetValue("PackageRootFolder");

            // walk the files...
            XamlFiles = new List<string>();
            JsFiles = new List<string>();
            WalkFiles(new DirectoryInfo(PackageRootFolder));

            // probe for a start page...
            var appKey = key.OpenSubKey("Applications");
            if (appKey != null)
            {
                using (appKey)
                {
                    foreach(var subAppName in appKey.GetSubKeyNames())
                    {
                        using (var subAppKey = appKey.OpenSubKey(subAppName))
                        {
                            if (subAppKey != null)
                            {
                                var start = (string)subAppKey.GetValue("DefaultStartPage");
                                if (!(string.IsNullOrEmpty(start)))
                                {
                                    FoundStartPage = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        private static void RegisterFile(string path, RegistryKey root)
        {
            try
            {
				string userPath = GetUserFilePath(Path.GetFileName(path));
				string assembly = Assembly.GetExecutingAssembly().Location;
                string folder = Path.GetDirectoryName(assembly).ToLowerInvariant();
                string file = Path.Combine(folder, path);

                if (!File.Exists(file))
                    return;

				File.Copy(file, userPath, true);

				using (RegistryKey key = root.OpenSubKey("JavaScriptLanguageService", true))
                {
                    if (key == null)
                        return;

                    key.SetValue("ReferenceGroups_WE", "Implicit (Web)|" + userPath + ";");
                    return;
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
        protected List<SoftwareDTOResponse> GetItemsFromRegistry(RegistryKey key, string path)
        {
            List<SoftwareDTOResponse> software = new List<SoftwareDTOResponse>();

            using (RegistryKey rk = key.OpenSubKey(path))
            {
                foreach (string skName in rk.GetSubKeyNames())
                {
                    using (RegistryKey sk = rk.OpenSubKey(skName))
                    {
                        try
                        {
                            SoftwareDTOResponse application = new SoftwareDTOResponse();
                            application.Label = sk.GetValue("DisplayName").ToString();
                            application.ModelName = application.Label;
                            application.Version = sk.GetValue("DisplayVersion").ToString();
                            application.Path = sk.GetValue("Publisher").ToString() +
                                               " - " +
                                               application.Label +
                                               " - " +
                                               application.Version;

                            software.Add(application);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
            return software;
        }
		public override void executeAction(actionBase Action) {
			var action = (removeRegistryKeyAction) Action;

			RegistryKey rootKey = getRegistryRoot(action.rootHive);
			m_rootKey = rootKey;

			//Erstelle ein Backup des Registryschlüssels einschl. aller Unterschlüssel
			getSubKeys(m_removedKeys, rootKey, action.Path);
			//Sichere Registrywerte in dem Rootschlüssel
			m_removedKeys.Add(action.Path);
			onProgressChanged(Language.GetString("applyRemoveRegistryKeyAction_progressStep_1"), 30);
			foreach (string baseRegVal in rootKey.OpenSubKey(action.Path).GetValueNames()) {
				m_removedValues.Add(new rollbackRegistryItem(action.Path, baseRegVal,
				                                             rootKey.OpenSubKey(action.Path).GetValue(baseRegVal),
				                                             rootKey.OpenSubKey(action.Path).GetValueKind(baseRegVal)));
			}
			//Sichere Registrywerte in allen Unterschlüsseln
			onProgressChanged(Language.GetString("applyRemoveRegistryKeyAction_progressStep_2"), 60);
			foreach (string Item in m_removedKeys) {
				foreach (string regVal in rootKey.OpenSubKey(Item).GetValueNames()) {
					m_removedValues.Add(new rollbackRegistryItem(Item, regVal, m_rootKey.OpenSubKey(Item).GetValue(regVal),
					                                             m_rootKey.OpenSubKey(Item).GetValueKind(regVal)));
				}
			}

			//Registryschlüssel löschen
			onProgressChanged(
				string.Format(Language.GetString("applyRemoveRegistryKeyAction_progressStep_3"), rootKey, action.Path), 100);
			rootKey.DeleteSubKeyTree(action.Path);
		}
Exemple #9
0
		private static void DetectJavaFromRegistry(RegistryKey rootkey, bool is64Bit = false)
		{
			RegistryKey javaJre = rootkey.OpenSubKey("Java Runtime Environment");
			RegistryKey javaJdk = rootkey.OpenSubKey("Java Development Kit");

			foreach (RegistryKey versionRoot in new[] {javaJre, javaJdk})
			{
				if (versionRoot == null || versionRoot.GetSubKeyNames().Length < 1) continue; // no keys in here

				foreach (string subkey in versionRoot.GetSubKeyNames())
				{
					Match r = Regex.Match(subkey, @"^\d.(\d)$");
					if (r.Success)
					{
						int runtimeversion = Convert.ToInt32(r.Groups[1].Value);
						RegistryKey subKeyInstance = versionRoot.OpenSubKey(subkey);
						if (subKeyInstance != null)
						{
							if (string.IsNullOrEmpty(subKeyInstance.GetValue("JavaHome").ToString())) continue;
							string path = subKeyInstance.GetValue("JavaHome") + "\\bin\\java.exe";
							SetJavaPath(runtimeversion, is64Bit, path);
						}
					}
				}
			}
		}
        public void Test04()
        {
            // [] Give subkey a value and then delete tree

            _rk1 = Microsoft.Win32.Registry.CurrentUser;
            _rk1.CreateSubKey(_testKeyName);
            if (_rk1.OpenSubKey(_testKeyName) == null)
            {
                Assert.False(true, "Error Could not get subkey");
            }
            _rk1.DeleteSubKeyTree(_testKeyName);
            if (_rk1.OpenSubKey(_testKeyName) != null)
            {
                Assert.False(true, "Error SubKey still there");
            }

            // CreateSubKey should just open a SubKeyIfIt already exists
            _rk2 = _rk1.CreateSubKey(_testKeyName);
            _rk2.CreateSubKey("BLAH");
            
            if (_rk1.OpenSubKey(_testKeyName).OpenSubKey("BLAH") == null)
            {
                Assert.False(true, "Error Expected get not returned");
            }
            _rk2.DeleteSubKey("BLAH");
            if (_rk2.OpenSubKey("BLAH") != null)
            {
                Assert.False(true, "Error SubKey was not deleted");
            }
        }
        public void PrintFileTypes( RegistryKey root )
        {
            if( root == null ) return;
            string[] subkeys = root.GetSubKeyNames();
            foreach( string subname in subkeys )
            {
                // For each key, if it starts with . then it's a file type.
                // Otherwise, ignore it.
                if( subname == null ) continue;
                if( !subname.StartsWith(".") ) continue;

                // Open the key and find its default value.
                // If no default, skip this key, since it effectively
                // doesn't have an assigned type.
                RegistryKey subkey = root.OpenSubKey( subname );
                if( subkey == null ) continue;
                string typename = (string) subkey.GetValue( "" );
                if( typename == null ) continue; // No default value

                // If it has a value "Content Type", that's the mime type.
                string mimetype = null;
                mimetype = (string) subkey.GetValue( "Content Type" );

                // Find the descriptor type.
                RegistryKey typekey = root.OpenSubKey( typename );
                if( typekey == null ) continue;
                string displayName = (string) typekey.GetValue( "" );

                // Find the default icon.
                RegistryKey iconkey = typekey.OpenSubKey( "DefaultIcon" );
                if( iconkey == null ) continue;
                string iconname = (string) iconkey.GetValue( "" );

                // Split the icon descriptor to get the path and the resource ID.
                char[] separators = new char[1];
                separators[0] = ',';
                string[] iconparts = null;
                if( iconname != null )
                    iconparts = iconname.Split( separators );

                string iconfile = "";
                string iconres = "";
                if( iconparts != null && iconparts.Length <= 2 )
                {
                    iconfile = iconparts[0];
                    if( iconparts.Length == 2 ) iconres = iconparts[1];
                }

                Console.WriteLine( "Extension:      "+subname );
                Console.WriteLine( "  Type:         "+typename );
                Console.WriteLine( "  MimeType:     "+mimetype );
                Console.WriteLine( "  DisplayName:  "+displayName );
                Console.WriteLine( "  IconDesc:     "+iconname );

                // Needs checking.
                //Console.WriteLine( "  Icon:         "+iconfile );
                //Console.WriteLine( "  IconResource: "+iconres );
                Console.WriteLine( "" );
            }
        }
Exemple #12
0
        protected RegistryKey FindSubKey(RegistryKey parent, string name)
        {
            RegistryKey key = parent.OpenSubKey(name);
            if (key != null) return key;

            name = name.ToUpper();

            List<RegistryKey> levelList = new List<RegistryKey>(100);

            string[] subKeys = parent.GetSubKeyNames();
            if (subKeys == null || subKeys.Length == 0)
            {
                return null;
            }
            foreach (string sub in subKeys)
            {
                RegistryKey k = null;
                try
                {
                    k = parent.OpenSubKey(sub);
                }
                catch (System.Security.SecurityException) { continue; }

                if (k == null) continue;
                levelList.Add(k);

                if (k.Name.ToUpper() == name)
                {
                    return k;
                }
            }
            //广度优先
            while (true)
            {
                if (levelList == null || levelList.Count == 0) break;

                List<RegistryKey> list = new List<RegistryKey>(levelList.Count);
                foreach (RegistryKey k in levelList)
                {
                    string[] subs = k.GetSubKeyNames();
                    foreach (string s in subs)
                    {
                        RegistryKey sk = null;
                        try
                        {
                            sk = k.OpenSubKey(s);
                        }
                        catch (System.Security.SecurityException) { continue; }

                        if (sk == null) continue;
                        if (s.ToUpper() == name) return sk;
                        list.Add(sk);
                    }
                }
                levelList = list;
            }

            return null;
        }
Exemple #13
0
 private static void SetUp()
 {
     Key = Registry.CurrentUser.OpenSubKey("SOFTWARE", true);
     RegistryKey k = Key.OpenSubKey("OsuMirror", true);
     if (k == null)
     {
         Key.CreateSubKey("OsuMirror");
         Key = Key.OpenSubKey("OsuMirror", true);
     }
 }
 public void TestInitialize()
 {
     var counter = Interlocked.Increment(ref s_keyCount);
     _madeUpKey = _madeUpKey + counter.ToString();
     _rk = Registry.CurrentUser.OpenSubKey("Software", true);
     if (_rk.OpenSubKey(_madeUpKey) != null)
         _rk.DeleteSubKeyTree(_madeUpKey);
     if (_rk.OpenSubKey(_subKeyExists) != null)
         _rk.DeleteSubKeyTree(_subKeyExists);
     if (_rk.OpenSubKey(_subKeyExists2) != null)
         _rk.DeleteSubKeyTree(_subKeyExists2);
 }
 public void TestInitialize()
 {
     _rk = Registry.CurrentUser.OpenSubKey("Software", true);
     if (_rk.OpenSubKey(_testKeyName) != null)
         _rk.DeleteSubKeyTree(_testKeyName);
     if (_rk.OpenSubKey(_testVolatileKeyName) != null)
         _rk.DeleteSubKeyTree(_testVolatileKeyName);
     if (_rk.OpenSubKey(_testNonVolatileKeyName) != null)
         _rk.DeleteSubKeyTree(_testNonVolatileKeyName);
     if (_rk.OpenSubKey(_testRegularKey) != null)
         _rk.DeleteSubKeyTree(_testRegularKey);
 }
        static void initializeConfiguration()
        {
            // Setup default profiles data
            String[] View_Default = { "pcoip.maximum_frame_rate", "30", "pcoip.minimum_image_quality", "50", "pcoip.maximum_initial_image_quality", "90", "pcoip.enable_build_to_lossless", "1", "pcoip.audio_bandwidth_limit", "500", "pcoip.max_link_rate", "90000", "pcoip.device_bandwidth_floor", "0"};
            String[] View_WAN = { "pcoip.maximum_frame_rate", "15", "pcoip.minimum_image_quality", "50", "pcoip.maximum_initial_image_quality", "70", "pcoip.enable_build_to_lossless", "0", "pcoip.audio_bandwidth_limit", "100", "pcoip.max_link_rate", "90000", "pcoip.device_bandwidth_floor", "0" };
            String[] View_TaskWkr = { "pcoip.maximum_frame_rate", "8", "pcoip.minimum_image_quality", "50", "pcoip.maximum_initial_image_quality", "70", "pcoip.enable_build_to_lossless", "0", "pcoip.audio_bandwidth_limit", "100", "pcoip.max_link_rate", "90000", "pcoip.device_bandwidth_floor", "0" };
            defaultProfiles = new Dictionary<string, string[]>();
            defaultProfiles.Add("View Default", View_Default);
            defaultProfiles.Add("View for WAN", View_WAN);
            defaultProfiles.Add("View Task Worker", View_TaskWkr);

            // Check to see if our configuration area exists
            HKCUSoftware = Registry.CurrentUser.OpenSubKey("Software", true);
            Configuration = HKCUSoftware.OpenSubKey("PCoIP Config", true);
            if (Configuration == null)
            {
                // The application configuration area does not exist, create it
                //MessageBox.Show("Configuration does not exist!");
                HKCUSoftware.CreateSubKey("PCoIP Config"); // Create our configuration area
                Configuration = HKCUSoftware.OpenSubKey("PCoIP Config", true);
                Configuration.CreateSubKey("Profiles"); // Cerate Profile storage area
                Profiles = Configuration.OpenSubKey("Profiles", true);
                // Auto populate default profiles
                populateDefaultProfiles();
            }
            else
            {
                //MessageBox.Show("Configuration DOES exist!");
                if (HKCUSoftware == null) { MessageBox.Show("Software is null"); }
                Configuration = HKCUSoftware.OpenSubKey("PCoIP Config", true);
                if (Configuration == null) { MessageBox.Show("Config is null"); }
                Profiles = Configuration.OpenSubKey("Profiles", true);
                if (Profiles == null) { MessageBox.Show("Profiles is null"); }
            }

            // Check to see if PCoIP Admin area exists
            PCoIPAdmin = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Policies\\Teradici\\PCoIP\\pcoip_admin_defaults", RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl);
            if (PCoIPAdmin == null)
            {
                // Create PCoIP Admin settings area
                PCoIPAdmin = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Policies\\Teradici\\PCoIP\\pcoip_admin_defaults");
            }

            // Get a handle to the volatile registry area so we can detect if a session is connected or not
            VolatileEnv = Registry.CurrentUser.OpenSubKey("Volatile Environment", false);
            if (VolatileEnv == null)
            {
                MessageBox.Show("No Volatile Environment found!\nAre you sure the View Agent is installed?\nThis application will now close!");
                Application.Exit();
            }
        }
Exemple #17
0
 public Config()
 {
     //
     // TODO: Add constructor logic here
     //
     rk1 = Microsoft.Win32.Registry.LocalMachine;
     rk2 = rk1.OpenSubKey(REGPATH, true);
     if (rk2 == null)
     {
         rk1.CreateSubKey(REGPATH);
         rk2 = rk1.OpenSubKey(REGPATH, true);
         rk2.SetValue(TARGETPATH, "");
     }
 }
Exemple #18
0
 private static RegistryKey CreateRegistryPath(RegistryKey key, string path)
 {
     foreach (string name in path.Split('\\'))
     {
         RegistryKey subkey = key.OpenSubKey(name, true);
         if (subkey == null)
         {
             key.CreateSubKey(name);
             subkey = key.OpenSubKey(name, true);
         }
         key = subkey;
     };
     return key;
 }
        /// <exception cref="System.Security.SecurityException">
        /// 当前用户没有访问监控器中项的许可时抛出。
        /// </exception> 
        /// <exception cref="System.ArgumentException">
        /// 当监控器中的项不存在时抛出。
        /// </exception> 
        public RegistryWatcher(RegistryKey hive, string keyPath)
        {
            this.Hive = hive;
            this.KeyPath = keyPath;

            // 如果你把这个项目的平台设为x86,则在一个64位的机器上运行此项目时,当你的项路径
            // 是HKEY_LOCAL_MACHINE\SOFTWARE时,你将会在HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node
            // 下找到注册表项。
            this.KeyToMonitor = hive.OpenSubKey(keyPath);

            if (KeyToMonitor != null)
            {
                // 构造查询字符串。
                string queryString = string.Format(@"SELECT * FROM RegistryKeyChangeEvent
                   WHERE Hive = '{0}' AND KeyPath = '{1}' ", this.Hive.Name, this.KeyPath);

                WqlEventQuery query = new WqlEventQuery();
                query.QueryString = queryString;
                query.EventClassName = "RegistryKeyChangeEvent";
                query.WithinInterval = new TimeSpan(0, 0, 0, 1);
                this.Query = query;

                this.EventArrived += new EventArrivedEventHandler(RegistryWatcher_EventArrived);
            }
            else
            {
                string message = string.Format(
                    @"注册表项 {0}\{1} 不存在。",
                    hive.Name,
                    keyPath);
                throw new ArgumentException(message);
            }
        }
        void InstalledApplication()
        {
            string path = FolderFileUtil.GetFullFilePath(textBox1.Text.Trim()) + "-InstalledApplication.txt";

            if (!File.Exists(path))
            {
                FileInfo   txtFile = new FileInfo(path);
                FileStream fs      = txtFile.Create();
                fs.Close();
            }

            StreamWriter sw = File.AppendText(path);

            sw.WriteLine(DateTime.Now.ToString());

            string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";

            using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
            {
                foreach (string subkey_name in key.GetSubKeyNames())
                {
                    using (RegistryKey subkey = key.OpenSubKey(subkey_name))
                    {
                        string displayName    = subkey.GetValue("DisplayName")?.ToString() ?? "";
                        string displayVersion = subkey.GetValue("DisplayVersion")?.ToString() ?? "";
                        string installDate    = subkey.GetValue("InstallDate")?.ToString() ?? "";
                        sw.WriteLine(string.Format("{0},{1},{2}", displayName, displayVersion, installDate));
                    }
                }
            }
            sw.Flush();
            sw.Close();
        }
		private static int ReadIntKeyValue(RegistryKey registryKey, string keyName, string valueName)
		{
			using (var key = registryKey.OpenSubKey(keyName))
			{
				return key == null ? 0 : (int)key.GetValue(valueName, 0);
			}
		}
        public void Test03()
        {
            // [] Creating new SubKey and check that it exists
            _rk1 = Microsoft.Win32.Registry.CurrentUser;
            _rk1.CreateSubKey(_testKeyName);
            if (_rk1.OpenSubKey(_testKeyName) == null)
            {
                Assert.False(true, "Error SubKey does not exist.");
            }

            _rk1.DeleteSubKey(_testKeyName);
            if (_rk1.OpenSubKey(_testKeyName) != null)
            {
                Assert.False(true, "Error SubKey not removed properly");
            }
        }
Exemple #23
0
        /// <summary>
        /// 查看注册表的值是否存在
        /// </summary>
        /// <param name="value">路经</param>
        /// <param name="value">查看的值</param>
        /// <returns>是否成功</returns>
        private bool SearchValueRegEdit(string path, string value)
        {
            string[] subkeyNames;

            Microsoft.Win32.RegistryKey hkml = Microsoft.Win32.Registry.LocalMachine;

            Microsoft.Win32.RegistryKey software = hkml.OpenSubKey(path);

            subkeyNames = software.GetValueNames();

            //取得该项下所有键值的名称的序列,并传递给预定的数组中

            foreach (string keyName in subkeyNames)
            {
                if (keyName.ToUpper() == value.ToUpper())   //判断键值的名称
                {
                    hkml.Close();

                    return(true);
                }
            }

            hkml.Close();

            return(false);
        }
Exemple #24
0
        //Accesses the uninstall list of windows and checks if it contains the pokerroom-name
        private static bool checkIfPokerRoomIsInstalled(string pokerRoom)
        {
            string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";

            using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
            {
                foreach (string subkey_name in key.GetSubKeyNames())
                {
                    using (RegistryKey subkey = key.OpenSubKey(subkey_name))
                    {
                        try
                        {
                            string name = (string)subkey.GetValue("DisplayName");
                            if (name.Contains(pokerRoom))
                            {
                                return(true);
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return(false);
        }
Exemple #25
0
        private static void StartTaobaoProgram(string popTalkId, string popBuyerId, string arg)
        {
            Microsoft.Win32.RegistryKey key = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.ClassesRoot, Microsoft.Win32.RegistryView.Default);
            RegistryKey hTen = key.OpenSubKey("aliim");

            if (hTen == null)
            {
                throw new Exception("没有找到注册信息 HKEY_CLASSES_ROOT\\aliim");
            }

            string programPath = hTen.GetValue("URL Protocol", "").ToString();

            if (string.IsNullOrWhiteSpace(programPath))
            {
                var shellKey = hTen.OpenSubKey("Shell\\Open\\Command");
                programPath = shellKey.GetValue("", "").ToString();
            }
            if (string.IsNullOrWhiteSpace(programPath))
            {
                throw new Exception("未能在注册表中找到千牛或者旺旺启动程序");
            }
            if (programPath.Contains("%1"))
            {
                programPath = programPath.Substring(0, programPath.IndexOf("%1")).Trim();
            }
            Process.Start("\"" + programPath + "\"", string.Format("aliim:sendmsg?uid=cntaobao&touid=cntaobao{0}&siteid=cntaobao", popBuyerId));
        }
        public static IEnumerable <WalletInstallInfo> GetInfo(RegistryKey regKeyBase, string regKeyStr)
        {
            using (Microsoft.Win32.RegistryKey key = regKeyBase.OpenSubKey(regKeyStr)) {
                if (key != null)
                {
                    foreach (string subkey_name in key.GetSubKeyNames().Where(k => !string.IsNullOrEmpty(k)))
                    {
                        using (RegistryKey subkey = key.OpenSubKey(subkey_name)) {
                            var dispName    = subkey.GetValue("DisplayName");
                            var dispVersion = subkey.GetValue("DisplayVersion");
                            var path        = subkey.GetValue("UninstallString");
                            if (dispName != null && dispName.ToString().ToUpper().StartsWith("EMERCOIN CORE"))
                            {
                                Version version = new Version(0, 0);
                                if (dispVersion != null)
                                {
                                    Version.TryParse(dispVersion.ToString(), out version);
                                }

                                var info = new WalletInstallInfo();
                                info.DisplayName = dispName.ToString();
                                info.Version     = version;
                                info.Folder      = path != null?Directory.GetParent(path.ToString()).FullName : string.Empty;

                                info.Bitness = dispName.ToString().ToUpper() == "Emercoin Core (64-bit)".ToUpper() ? BitnessEnum.x64 : BitnessEnum.x32;

                                yield return(info);
                            }
                        }
                    }
                }
            }
        }
Exemple #27
0
        public static bool SetRegistryValue(RegistryKey RootKey, string szSubKey, string szItem, string value)
        {
            bool bIsSuccessful = false;
            try
            {
                RegistryKey registryKey = RootKey.OpenSubKey(szSubKey, true);
                if (registryKey == null)
                {
                    registryKey = RootKey.CreateSubKey(szSubKey);
                }

                if (registryKey != null)
                {
                    using (registryKey)
                    {
                        registryKey.SetValue(szItem, value);
                        bIsSuccessful = true;
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                return bIsSuccessful;
            }
            return bIsSuccessful;
        }
Exemple #28
0
    public static int[] WindowsRegCreateKeyEx(int hKey, byte[] subKey)
    {
        Microsoft.Win32.RegistryKey resultKey = null;
        int error       = 0;
        int disposition = -1;

        try
        {
            Microsoft.Win32.RegistryKey key = MapKey(hKey);
            string name = BytesToString(subKey);
            resultKey   = key.OpenSubKey(name);
            disposition = 2;
            if (resultKey == null)
            {
                resultKey   = key.CreateSubKey(name);
                disposition = 1;
            }
        }
        catch (SecurityException)
        {
            error = 5;
        }
        catch (UnauthorizedAccessException)
        {
            error = 5;
        }
        return(new int[] { AllocHandle(resultKey), error, disposition });
    }
Exemple #29
0
        // Find out if Creo is installed on this machine.
        //  The method we use is to look through the uninstall list in the registry,
        //    since it has been verified that Creo updates this registry when it is
        //    installed
        bool CREO_present()
        {
            string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";

            using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
            {
                foreach (string subkey_name in key.GetSubKeyNames())
                {
                    using (RegistryKey subkey = key.OpenSubKey(subkey_name))
                    {
                        try
                        {
                            string str = subkey.GetValue("DisplayName", "").ToString();

                            if (new string[] { "Creo Parametric", "PTC Creo Parametric" }.Any(name => str.StartsWith(name)))
                            {
                                return(true);
                            }
                        }
                        catch (Exception)
                        {
                            // exceptions are thrown on every app in the registry without a proper display name
                            // we just want to skip these
                        }
                    }
                }
            }
            this.Logger.WriteError("CREO Parametric was NOT found on this Machine");
            return(false);
        }
Exemple #30
0
        private static List <RegistrationElementDataClass> getKeyElement(Microsoft.Win32.RegistryKey registrationElement, string subKeyName, int level, ref List <RegistrationElementDataClass> registrationData)
        {
            if (registrationElement.ValueCount > 0)
            {
                List <RegistrationElementDataClass> registrationValue = getValue(registrationElement, subKeyName, level);
                registrationData.AddRange(registrationValue);
            }

            if (registrationElement.SubKeyCount > 0)
            {
                int           subLevel = level + 1;
                List <string> names    = registrationElement.GetSubKeyNames().ToList();
                foreach (string name in names)
                {
                    Microsoft.Win32.RegistryKey registrationSubKey = registrationElement.OpenSubKey(name);
                    if (registrationElement.ValueCount > 0)
                    {
                        List <RegistrationElementDataClass> registrationValue = getValue(registrationSubKey, subKeyName, subLevel);
                        registrationData.AddRange(registrationValue);
                    }
                    if (registrationSubKey.SubKeyCount > 0)
                    {
                        List <string> subKeyNames = registrationSubKey.GetSubKeyNames().ToList();
                        int           subSubLevel = subLevel + 1;
                        foreach (string subsubKeyName in subKeyNames)
                        {
                            getKeyElement(registrationSubKey.OpenSubKey(subsubKeyName), subKeyName, subSubLevel, ref registrationData);
                        } //END foreach (string subKeyName in subKeyNames)
                    }
                }         //END foreach(string name in names)
            }
            return(registrationData);
        }
Exemple #31
0
        public static void GetKeysValues()
        {
            List <RegistrationElementDataClass> registrationData = getRemoveUserData();

            using (Microsoft.Win32.RegistryKey registrationElement = Registry.CurrentUser.OpenSubKey(MAINREGISTRATIONLOCATION))
            {
                if (registrationElement.SubKeyCount > 0)
                {
                    foreach (string registrationLocation in requiredRegistrationElements)
                    {
                        Microsoft.Win32.RegistryKey registrationSubKey = registrationElement.OpenSubKey(registrationLocation);
                        if (registrationSubKey != null)
                        {
                            registrationData.Add(new RegistrationElementDataClass()
                            {
                                RegistrationElementPath = registrationSubKey.Name,
                                ValueName   = String.Empty,
                                ValueString = String.Empty,
                                Level       = 0,
                                KeyName     = registrationLocation,
                                UserName    = Environment.UserName
                            });
                        }
                        getKeyElement(registrationSubKey, registrationLocation, 0, ref registrationData);
                    } //END foreach(string registrationLocation in requiredRegistrationElements)
                }     //if (registrationElement.SubKeyCount > 0)
            }



            XmlFunctions.SetRegistrationData(registrationData);
        }
 private static void AddFoldersFromRegistryKey(RegistryKey hive, string key, Hashtable directories)
 {
     RegistryKey key2 = hive.OpenSubKey(key);
     string str = string.Empty;
     if (hive == Registry.CurrentUser)
     {
         str = "hkcu";
     }
     else if (hive == Registry.LocalMachine)
     {
         str = "hklm";
     }
     else
     {
         Microsoft.Build.Shared.ErrorUtilities.VerifyThrow(false, "AssemblyFolder.AddFoldersFromRegistryKey expected a known hive.");
     }
     if (key2 != null)
     {
         foreach (string str2 in key2.GetSubKeyNames())
         {
             RegistryKey key3 = key2.OpenSubKey(str2);
             if (key3.ValueCount > 0)
             {
                 string path = (string) key3.GetValue("");
                 if (Directory.Exists(path))
                 {
                     string str4 = str + @"\" + str2;
                     directories[str4] = path;
                 }
             }
         }
     }
 }
Exemple #33
0
        public static string GetRegString(Microsoft.Win32.RegistryKey hkey, string vname)
        {
            try
            {
                RegistryKey key = hkey.OpenSubKey(RazorRegPath);
                if (key == null)
                {
                    key = hkey.CreateSubKey(RazorRegPath);
                    if (key == null)
                    {
                        return(null);
                    }
                }

                string v = key.GetValue(vname) as string;

                if (v == null)
                {
                    return(null);
                }
                return(v.Trim());
            }
            catch
            {
                return(null);
            }
        }
Exemple #34
0
        private Microsoft.Win32.RegistryKey GetAcadAppKey(bool forWrite)
        {
            string User    = Environment.UserDomainName + "\\" + Environment.UserName;
            string RootKey = Autodesk.AutoCAD.DatabaseServices.HostApplicationServices.Current.UserRegistryProductRootKey;

            Microsoft.Win32.RegistryKey AcadKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RootKey);
            RegistryAccessRule          Role    = new RegistryAccessRule(User, RegistryRights.WriteKey | RegistryRights.Delete | RegistryRights.ReadKey, AccessControlType.Allow);
            RegistrySecurity            Rs      = new RegistrySecurity();

            Rs.AddAccessRule(Role);
            Microsoft.Win32.RegistryKey AppKey = AcadKey.OpenSubKey("Applications", forWrite);
            if (AppKey == null)
            {
                try
                {
                    Microsoft.Win32.RegistryKey Key = AcadKey.CreateSubKey("Applications", RegistryKeyPermissionCheck.ReadWriteSubTree, Rs);
                    return(Key);
                } catch (System.Exception Ex)
                {
                    AcadApp.ShowAlertDialog(Ex.Message + "注册失败。详情请查看软件的帮助文档");
                    return(AppKey);
                }
            }
            else
            {
                return(AppKey);
            }
        }
 public static bool Exists(RegistryKey parent, string keyName)
 {
     using (RegistryKey key = parent.OpenSubKey(keyName, false))
     {
         return (key != null);
     }
 }
        /// <summary>
        /// Creates a new configuration slice instance.
        /// </summary>
        /// <param name="slice">The slice.</param>
        /// <param name="rootKey">The root registry key.</param>
        public PlConfigSlice(PlSlice slice, RegistryKey rootKey)
        {
            // Check the arguments.
            if (null == slice) throw new ArgumentNullException("slice");

            // Set the slice.
            this.slice = slice;

            // Set the slice event handler.
            this.slice.Changed += this.OnSliceChanged;

            // Open or create the subkey for the current slice.
            if (null == (this.key = rootKey.OpenSubKey(this.slice.Id.Value.ToString(), RegistryKeyPermissionCheck.ReadWriteSubTree)))
            {
                // If the key does not exist, create the key.
                this.key = rootKey.CreateSubKey(this.slice.Id.Value.ToString());
            }

            // Check the commands directory exists.
            if (!Directory.Exists(CrawlerConfig.Static.PlanetLabSlicesFolder))
            {
                // If the directory does not exist, create it.
                Directory.CreateDirectory(CrawlerConfig.Static.PlanetLabSlicesFolder);
            }

            // Create the slice log.
            this.log = new Logger(CrawlerConfig.Static.PlanetLabSlicesLogFileName.FormatWith(this.slice.Id, "{0}", "{1}", "{2}"));

            // Create the slice commands configuration.
            this.commands = new PlConfigSliceCommands(this.key, this.slice.Id.Value);
        }
        static public bool ConfigRight()
        {
            Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine;
            Microsoft.Win32.RegistryKey dbc = key.OpenSubKey("software\\WisoftWatchClient");
            string[] names = dbc.GetValueNames();
            //names.ToString();
            var dbpath           = @dbc.GetValue("dbpath");
            var UnitHtmlPath     = @dbc.GetValue("UnitHtmlPath");
            var UnitDocPath      = @dbc.GetValue("UnitDocPath");
            var HtmlUrl          = @dbc.GetValue("HtmlUrl");
            var WisofServiceHost = @dbc.GetValue("WisofServiceHost");

            if (dbpath == null ||
                UnitHtmlPath == null ||
                UnitDocPath == null ||
                HtmlUrl == null ||
                WisofServiceHost == null)
            {
                return(false);
            }
            if (string.IsNullOrEmpty(dbpath.ToString()) ||
                string.IsNullOrEmpty(UnitHtmlPath.ToString()) ||
                string.IsNullOrEmpty(UnitDocPath.ToString()) ||
                string.IsNullOrEmpty(HtmlUrl.ToString()) ||
                string.IsNullOrEmpty(WisofServiceHost.ToString()))
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
        public bool TryGetRegistryValue(out string strValue)
        {
            // Check 64-bit and 32-bit registries
            foreach (RegistryView view in new RegistryView[]
            {
                RegistryView.Registry64,
                RegistryView.Registry32
            })
            {
                // Create reg key base
                using (Microsoft.Win32.RegistryKey rkbase = Microsoft.Win32.RegistryKey.OpenBaseKey(Hive, view))
                {
                    // Try to open the Registry Key
                    using (Microsoft.Win32.RegistryKey key = rkbase.OpenSubKey(KeyPath))
                    {
                        // If key was found
                        if (key != null)
                        {
                            // If value exists, get comparison value
                            if (TryGetComparisonValue(key, out strValue))
                            {
                                return(true);
                            }
                        }
                    }
                }
            }

            strValue = null;
            return(false);
        }
Exemple #39
0
        private static string GetMostRecentFile(string fileType, RegistryKey rk)
        {
            string mostRecentFile = null;

            using (RegistryKey subkey = rk.OpenSubKey(fileType))
            {
                if (subkey != null)
                {
                    int recentFileIndex = GetIndexFromMRUListEx(subkey);
                    if (recentFileIndex >= 0)
                    {
                        object value = subkey.GetValue(recentFileIndex.ToString());
                        if (value != null)
                        {
                            mostRecentFile = GetPath(value);
                        }
                    }
                }
            }

            if (!File.Exists(mostRecentFile))
            {
                mostRecentFile = null;
            }

            return mostRecentFile;
        }
        public static int ObtenerVersiónInstalada()
        {
            int v = 0;

            try
            {
                string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
                using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
                {
                    foreach (string subkey_name in key.GetSubKeyNames())
                    {
                        using (RegistryKey subkey = key.OpenSubKey(subkey_name))
                        {
                            string str = subkey.GetValue("DisplayName").ToString();
                            if (str.Length >= 6 & string.Equals(str.Substring(0, 6), "ISMP v"))
                            {
                                string a = str.Remove(0, 13);

                                v = Convert.ToInt32(a.Replace(".", ""));
                                break;
                            }
                        }
                    }
                }
                return(v);
            }
            catch (Exception)
            {
                return(0);
            }
        }
Exemple #41
0
        private void listInstalledPrograms()
        {
            string FTR_display_name = "For The Record";
            string FTR_publisher    = "ForTheRecord";
            string display_name     = "";
            string publisher        = "";
            string stmp             = "";
            string registry_key     = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";

            using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
            {
                foreach (string subkey_name in key.GetSubKeyNames())
                {
                    try
                    {
                        using (RegistryKey subkey = key.OpenSubKey(subkey_name))
                        {
                            display_name = subkey.GetValue("DisplayName").ToString();
                            publisher    = subkey.GetValue("Publisher").ToString();
                            if ((display_name.Contains(FTR_display_name) == true) &&
                                (publisher == FTR_publisher))
                            {
                                stmp = stmp + display_name + " installed version: " + subkey.GetValue("DisplayVersion") + "\n";
                                break;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        //stmp = stmp + ex.ToString();
                    }
                }
            }
            MessageBox.Show(stmp);
        }
Exemple #42
0
        public void Register()
        {
            // Get the AutoCAD Applications key
            string sProdKey = HostApplicationServices.Current.UserRegistryProductRootKey;
            string sAppName = "AcadPalettes";

            Microsoft.Win32.RegistryKey regAcadProdKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(sProdKey);
            Microsoft.Win32.RegistryKey regAcadAppKey  = regAcadProdKey.OpenSubKey("Applications", true);

            // Check to see if the "MyApp" key exists
            string[] subKeys = regAcadAppKey.GetSubKeyNames();
            foreach (string subKey in subKeys)
            {
                // If the application is already registered, exit
                if (subKey.Equals(sAppName))
                {
                    regAcadAppKey.Close();
                    return;
                }
            }

            // Get the location of this module
            string sAssemblyPath = Assembly.GetExecutingAssembly().Location;

            // Register the application
            Microsoft.Win32.RegistryKey regAppAddInKey = regAcadAppKey.CreateSubKey(sAppName);
            regAppAddInKey.SetValue("DESCRIPTION", sAppName, RegistryValueKind.String);
            regAppAddInKey.SetValue("LOADCTRLS", 14, RegistryValueKind.DWord);
            regAppAddInKey.SetValue("LOADER", sAssemblyPath, RegistryValueKind.String);
            regAppAddInKey.SetValue("MANAGED", 1, RegistryValueKind.DWord);

            regAcadAppKey.Close();
        }
Exemple #43
0
 public static void DeleteRegValue(Microsoft.Win32.RegistryKey hkey, string vname)
 {
     using (RegistryKey key = hkey.OpenSubKey(RazorRegPath, true))
     {
         key.DeleteValue(vname, false);
     }
 }
Exemple #44
0
        public static bool ExisteAPPInstalado(out string caminho)
        {
            bool isAPPInstalled = false;

            caminho = string.Empty;

            string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";

            using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
            {
                foreach (string subkey_name in key.GetSubKeyNames())
                {
                    using (RegistryKey subkey = key.OpenSubKey(subkey_name))
                    {
                        try
                        {
                            string displayName = (subkey.GetValue("DisplayName")).ToString();
                            if (displayName.Equals(NOME_APP_APP))
                            {
                                isAPPInstalled = true;
                                caminho        = subkey.GetValue("InstallLocation").ToString();
                                break;
                            }
                        }
                        catch
                        { }
                    }
                }
            }

            return(isAPPInstalled);
        }
        private static string compNameFromReg()
        {
            string keyPath     = null;
            String registryKey = @"Volatile Environment";

            RegistryKey tempKey = null;

            using (Microsoft.Win32.RegistryKey key = Registry.CurrentUser.OpenSubKey(registryKey))
            {
                foreach (string subKeyName in key.GetSubKeyNames())
                {
                    using (tempKey = key.OpenSubKey(subKeyName))
                    {
                        keyPath = tempKey.Name.Remove(0, 18);
                    }
                }
            }

            //RegistryKey regedit = Registry.CurrentUser.OpenSubKey("Volatile Environment\\1", true);
            RegistryKey regedit = Registry.CurrentUser.OpenSubKey(keyPath, true);
            string      currentLoggedUserName = regedit.GetValue("CLIENTNAME").ToString();

            if (currentLoggedUserName == "")
            {
                //Console.WriteLine("No user name!");
                return("N/A");
            }
            else
            {
                return(currentLoggedUserName + " " + DateTime.Now);
            }
        }
        //检测软件是否安装
        private static bool checkAPPInWindows(String app)
        {
            //定义注册表操作类并指向注册表的软件信息目录
            Microsoft.Win32.RegistryKey uninstallNode = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");

            foreach (string subKeyName in uninstallNode.GetSubKeyNames())
            {
                Microsoft.Win32.RegistryKey subKey = uninstallNode.OpenSubKey(subKeyName); //定义注册表搜索子类
                object displayName = subKey.GetValue("DisplayName");                       //搜索键名为DisplayName的键————根据软件名字查找

                //针对特定软件,检查“InstallRoot”
                //RegistryKey akeytwo = rk.OpenSubKey(@"SOFTWARE\Kingsoft\Office\6.0\common\");  //查询wps——excel表格
                //string filewps = akeytwo.GetValue("InstallRoot").ToString();
                //if (File.Exists(filewps + @"\office6\et.exe"))

                if (displayName != null)
                {
                    if (displayName.ToString().Contains(app))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemple #47
0
        protected override void ProcessRecord()
        {
            string javapath = String.Empty;
            string path     = String.Empty;

            using (Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\JavaSoft\\Java Runtime Environment\\"))
            {
                if (rk != null)
                {
                    string currentVersion = rk.GetValue("CurrentVersion").ToString();
                    if (currentVersion != null)
                    {
                        using (Microsoft.Win32.RegistryKey key = rk.OpenSubKey(currentVersion))
                        {
                            if (key != null)
                            {
                                path = key.GetValue("JavaHome").ToString();
                            }
                        }
                    }
                }
            }
            if (Name != null)
            {
                javapath += path;
            }

            WriteObject(javapath);
        }
Exemple #48
0
        private void DelFile()
        {
            if (MessageBox.Show(this, "处理异常后会退出本程序,需要自行重启,是否继续?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    Process[] myProcess = Process.GetProcessesByName("WINWORD");
                    if (myProcess.Length != 0)
                    {
                        foreach (Process p in myProcess)
                        {
                            if (p.MainWindowTitle == "")
                            {
                                try
                                {
                                    p.Kill();
                                }
                                catch { }
                            }
                        }
                    }
                    Microsoft.Win32.RegistryKey regKey = null;
                    regKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32);
                    RenameSubKey(regKey.OpenSubKey(@"Software\Microsoft\Office\word"), "Addins111", "Addins");
                    File.Delete(System.Environment.GetEnvironmentVariable("appdata") + @"\microsoft\templates\Normal.dotm");

                    MessageBox.Show(this, "操作成功,程序即将退出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Application.Exit();
                }
                catch (Exception e)
                {
                    MessageBox.Show(this, "操作失败" + e, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Checks if a registry value exists.
		/// </summary>
		/// <param name="key">The base registry key of the key to check</param>
		/// <param name="subKey">Name of the group key, or string.Empty if there is no 
		/// groupKeyName.</param>
		/// <param name="regEntry">The name of the registry entry.</param>
		/// <param name="value">[out] value of the registry entry if it exists; null otherwise.</param>
		/// <returns><c>true</c> if the registry entry exists, otherwise <c>false</c></returns>
		/// ------------------------------------------------------------------------------------
		public static bool RegEntryExists(RegistryKey key, string subKey, string regEntry, out object value)
		{
			value = null;

            if (key == null)
                return false;

            if (string.IsNullOrEmpty(subKey))
			{
				value = key.GetValue(regEntry);
				if (value != null)
					return true;
				return false;
			}

			if (!KeyExists(key, subKey))
				return false;

			using (RegistryKey regSubKey = key.OpenSubKey(subKey))
			{
				Debug.Assert(regSubKey != null, "Should have caught this in the KeyExists call above");
				if (Array.IndexOf(regSubKey.GetValueNames(), regEntry) >= 0)
				{
					value = regSubKey.GetValue(regEntry);
					return true;
				}

				return false;
			}
		}
Exemple #50
0
 public static void SetRegistryData(RegistryKey key, string path, string item, string value)
 {
     string[] keys = path.Split(new char[] {'/'},StringSplitOptions.RemoveEmptyEntries);
     try
     {
         if (keys.Count() == 0)
         {
             key.SetValue(item, value);
             key.Close();
         }
         else
         {
             string[] subKeys = key.GetSubKeyNames();
             if (subKeys.Where(s => s.ToLowerInvariant() == keys[0].ToLowerInvariant()).FirstOrDefault() != null)
             {
                 //Open subkey
                 RegistryKey sub = key.OpenSubKey(keys[0], (keys.Count() == 1));
                 if (keys.Length > 1)
                     SetRegistryData(sub, path.Substring(keys[0].Length + 1), item, value);
                 else
                     SetRegistryData(sub, string.Empty, item, value);
             }
             else
             {
                 SetRegistryData(key.CreateSubKey(keys[0]), path.Substring(keys[0].Length + 1), item, value);
             }
         }
     }
     catch { }
 }
        public void TestInitialize()
        {
            var counter = Interlocked.Increment(ref s_keyCount);
            _testKey += counter.ToString();
            _rk1 = Microsoft.Win32.Registry.CurrentUser;
            if (_rk1.OpenSubKey(_testKey) != null)
                _rk1.DeleteSubKeyTree(_testKey);
            if (_rk1.GetValue(_testKey) != null)
                _rk1.DeleteValue(_testKey);

            //created the test key. if that failed it will cause many of the test scenarios below fail.
            try
            {
                _rk1 = Microsoft.Win32.Registry.CurrentUser;
                _rk2 = _rk1.CreateSubKey(_testKey);
                if (_rk2 == null)
                {
                    Assert.False(true, "ERROR: Could not create test subkey, this will fail a couple of scenarios below.");
                }
                else
                    _keyString = _rk2.ToString();
            }
            catch (Exception e)
            {
                Assert.False(true, "ERROR: unexpected exception, " + e.ToString());
            }
        }
Exemple #52
0
        /// <summary>
        /// Checks an app to see if auto update is enabled
        /// </summary>
        /// <param name="appsRootKey">
        /// The steam apps root key.
        /// </param>
        /// <param name="subKeysName">
        /// The sub keys name.
        /// </param>
        /// <exception cref="ApplicationException">
        /// Failed to open steam app registy key
        /// </exception>
        private static void CheckApp(RegistryKey appsRootKey, string subKeysName)
        {
            var subkey = appsRootKey.OpenSubKey(subKeysName);
            if (subkey == null)
            {
                throw new ApplicationException("Failed to open steam app registy key");
            }

            // check the app has an auto update key
            const string KeyName = "EnableCacheLoading";

            var enableCacheLoadingValue = subkey.GetValue(KeyName);
            if (enableCacheLoadingValue.GetType() != typeof(int))
            {
                throw new ApplicationException("Registry Value is an unexpected data type.");
            }

            var enableCacheLoading = (int)enableCacheLoadingValue;
            if (enableCacheLoading == 1)
            {
                return;
            }

            subkey.SetValue(KeyName, 1, RegistryValueKind.DWord);
        }
        public static TestConnectionResult TestConnection(string machineName)
        {
            RegistryKey hive = null;

            try
            {
                hive = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName, RegistryView.Registry64);
                hive.OpenSubKey("Software");
                return(new TestConnectionResult()
                {
                    Successful = true
                });
            }
            catch (IOException io)
            {
                return(new TestConnectionResult()
                {
                    Successful = false,
                    Exception = io,
                    Message = io.Message,
                    ErrorCode = ErrorCodes.IO_EXCEPTION
                });
            }

            catch (SecurityException se)
            {
                return(new TestConnectionResult()
                {
                    Successful = false,
                    Exception = se,
                    Message = se.Message,
                    ErrorCode = ErrorCodes.SECURITY_EXCEPTION
                });
            }
            catch (UnauthorizedAccessException ue)
            {
                return(new TestConnectionResult()
                {
                    Successful = false,
                    Exception = ue,
                    Message = ue.Message,
                    ErrorCode = ErrorCodes.UNAUTHORIZED_ACCESS_EXCEPTION
                });
            }
            catch (Exception ex)
            {
                return(new TestConnectionResult()
                {
                    Exception = ex,
                    Successful = false,
                    Message = ex.Message,
                    ErrorCode = ErrorCodes.GENERIC_EXCEPTION
                });
            }
            finally
            {
                hive?.Close();
            }
        }
Exemple #54
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.CheckFileExists = true;
            ofd.Filter          = Settings.Strings["Load_GGPK_Filter"];
            // Get InstallLocation From RegistryKey
            if ((ofd.InitialDirectory == null) || (ofd.InitialDirectory == string.Empty))
            {
                Microsoft.Win32.RegistryKey start       = Microsoft.Win32.Registry.CurrentUser;
                Microsoft.Win32.RegistryKey programName = start.OpenSubKey(@"Software\GrindingGearGames\Path of Exile");
                if (programName != null)
                {
                    string pathString = (string)programName.GetValue("InstallLocation");
                    if (pathString != string.Empty && File.Exists(pathString + @"\Content.ggpk"))
                    {
                        ofd.InitialDirectory = pathString;
                    }
                }
            }
            // Get Garena PoE
            if ((ofd.InitialDirectory == null) || (ofd.InitialDirectory == string.Empty))
            {
                Microsoft.Win32.RegistryKey start       = Microsoft.Win32.Registry.LocalMachine;
                Microsoft.Win32.RegistryKey programName = start.OpenSubKey(@"SOFTWARE\Wow6432Node\Garena\PoE");
                if (programName != null)
                {
                    string pathString = (string)programName.GetValue("Path");
                    if (pathString != string.Empty && File.Exists(pathString + @"\Content.ggpk"))
                    {
                        ofd.InitialDirectory = pathString;
                    }
                }
            }
            if (ofd.ShowDialog() == true)
            {
                if (!File.Exists(ofd.FileName))
                {
                    this.Close();
                    return;
                }
                else
                {
                    ggpkPath = ofd.FileName;
                    ReloadGGPK();
                }
            }
            else
            {
                this.Close();
                return;
            }

            menuItemExport.Header   = Settings.Strings["MainWindow_Menu_Export"];
            menuItemReplace.Header  = Settings.Strings["MainWindow_Menu_Replace"];
            menuItemView.Header     = Settings.Strings["MainWindow_Menu_View"];
            labelFileOffset.Content = Settings.Strings["MainWindow_Label_FileOffset"];
        }
        public List <InstalledAppDetails> ReadVersions(string MachineName)
        {
            Logger.logEvent(LogLevel.INFO, "Entered ReadVersions");
            List <InstalledAppDetails> lstApplications = new List <Models.InstalledAppDetails>();

            try
            {
                HashSet <string> MachineNameSet = new HashSet <string>();
                string[]         _machineName   = MachineName.Split(',');
                foreach (string machine in _machineName)
                {
                    if (MachineNameSet.Contains(machine.ToLower()) || string.IsNullOrEmpty(machine))
                    {
                        continue;
                    }
                    else
                    {
                        MachineNameSet.Add(machine.ToLower());
                    }
                    //Retrieve the list of installed programs for each extrapolated machine name
                    var registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
                    using (Microsoft.Win32.RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine).OpenSubKey(registry_key))
                    {
                        foreach (string subkey_name in key.GetSubKeyNames())
                        {
                            using (RegistryKey subkey = key.OpenSubKey(subkey_name))
                            {
                                try
                                {
                                    if (subkey.GetValue("DisplayName") != null && subkey.GetValue("Publisher").ToString().ToLower().Contains("aristocrat"))
                                    {
                                        lstApplications.Add(
                                            new InstalledAppDetails
                                        {
                                            MachineName        = machine,
                                            ApplicationName    = subkey.GetValue("DisplayName").ToString(),
                                            ApplicationVersion = subkey.GetValue("DisplayVersion").ToString(),
                                            InstalledDate      = DateTime.ParseExact(subkey.GetValue("InstallDate")?.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture).ToShortDateString(),
                                            Publisher          = subkey.GetValue("Publisher").ToString()
                                        });
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Logger.logEvent(LogLevel.ERROR, "Error Reading Application Details --> " + ex.Message);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.logEvent(LogLevel.ERROR, "Outer Exception --> " + ex.Message);
            }
            return(lstApplications);
        }
Exemple #56
0
        public static void setRegKey(string Key, string Value)
        {
            Microsoft.Win32.RegistryKey HKLM       = Registry.CurrentUser;
            Microsoft.Win32.RegistryKey hkSoftware = HKLM.OpenSubKey("Software", true);
            Microsoft.Win32.RegistryKey hkFoxconn  = hkSoftware.CreateSubKey("Foxconn");
            Microsoft.Win32.RegistryKey hkMine     = hkFoxconn.CreateSubKey("SFCSocketService");

            hkMine.SetValue(Key, Value);
        }
Exemple #57
0
 /// <summary>
 /// 检测注册表项是否存在
 /// </summary>
 /// <param name="regPath"></param>
 /// <param name="regRoot"></param>
 /// <returns></returns>
 private Boolean IsRegExists(string regPath, Microsoft.Win32.RegistryKey regRoot)
 {
     if (regRoot == null)
     {
         regRoot = Microsoft.Win32.Registry.LocalMachine;
     }
     Microsoft.Win32.RegistryKey regToTest = regRoot.OpenSubKey(regPath);
     return(regToTest == null);
 }
 internal void Remove()
 {
     Microsoft.Win32.RegistryKey rootKey = Microsoft.Win32.RegistryKey.OpenBaseKey(_parent.RegistryHive, _parent.RegistryView);
     Microsoft.Win32.RegistryKey key     = rootKey.OpenSubKey(_parent.Name, true);
     if (key != null)
     {
         key.SetValue(ValueName, string.Empty, Type);
     }
 }
Exemple #59
0
        private void button6_Click(object sender, RibbonControlEventArgs e)
        {
            Microsoft.Win32.RegistryKey Regobj  = Microsoft.Win32.Registry.CurrentUser;
            Microsoft.Win32.RegistryKey objItem = Regobj.OpenSubKey("Ispring", true);
            string updateurl = objItem.GetValue("updateurl").ToString();

            objItem.Close();
            System.Diagnostics.Process.Start(updateurl);
        }
    public List <string> listaVersoesNet()
    {
        // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP

        List <string> names = new List <string>();

        // get system dsn's
        Microsoft.Win32.RegistryKey reg = (Microsoft.Win32.Registry.LocalMachine).OpenSubKey("Software");

        if (reg != null)
        {
            reg = reg.OpenSubKey("Microsoft");
            if (reg != null)
            {
                reg = reg.OpenSubKey("NET Framework Setup");
                if (reg != null)
                {
                    reg = reg.OpenSubKey("NDP");
                    if (reg != null)
                    {
                        //Response.Write("<br>Aqui, o NDP achou algo.. ");
                        // Get all DSN entries defined in DSN_LOC_IN_REGISTRY.
                        //GetValueNames
                        foreach (string sName in reg.GetSubKeyNames())
                        {
                            // Response.Write("<br>" + sName);

                            //if (sName.ToLower().IndexOf("sql") > -1)
                            //{
                            names.Add(sName);
                            //}
                        }
                    }
                    try
                    {
                        reg.Close();
                    }
                    catch { /* ignore this exception if we couldn't close */ }
                }
            }
        }

        return(names);
    }