/// <summary> /// 解压缩 /// </summary> /// <param name="zipname">要解压的文件名</param> /// <param name="zippath">要解压的文件路径</param> public static void DeZip(string zipname, string zippath) { try { the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command"); the_Obj = the_Reg.GetValue(""); the_rar = the_Obj.ToString(); the_Reg.Close(); the_rar = the_rar.Substring(1, the_rar.Length - 7); the_Info = " X " + zipname + " " + zippath; the_StartInfo = new ProcessStartInfo(); the_StartInfo.FileName = the_rar; the_StartInfo.Arguments = the_Info; the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden; the_Process = new Process(); the_Process.StartInfo = the_StartInfo; the_Process.Start(); the_Process.WaitForExit(); the_Process.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } }
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; }
/// <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); }
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(); }
private void AddToAutostart(bool enabled, string name) { string Path = Directory.GetCurrentDirectory(); string yourKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; Microsoft.Win32.RegistryKey startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(yourKey); if (enabled) { if (startupKey.GetValue(name) == null) { startupKey.Close(); startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(yourKey, true); // Add startup reg key startupKey.SetValue(name, Path.ToString()); startupKey.Close(); } } else { // remove startup startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(yourKey, true); startupKey.DeleteValue(name, false); startupKey.Close(); } }
private void SyncWallpaper() { // open the dekstop registry key Microsoft.Win32.RegistryKey DesktopKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop"); // read the last converted wallpaper (in case the new wallpaper is a JPEG converted to wallpaper1.bmp) string LastConvertedWallpaperPathNew = (string)DesktopKey.GetValue("ConvertedWallpaper"); // read the actual wallpaper path string WallpaperPathNew = (string)DesktopKey.GetValue("Wallpaper"); DesktopKey.Close(); if (WallpaperPathNew == "" || WallpaperPathNew == null) { return; } // if the WallpaperPath has changed, then the user set a new BMP // if the LastConvertedWallpaper changed, then the user set a new JPEG (BMP name doesn't necessarily change if previous wallpaper was a JPEG too) if (WallpaperPathNew != WallpaperPath || LastConvertedWallpaperPathNew != LastConvertedWallpaperPath) { // load new bg SetBg(WallpaperPathNew); // update the image information Microsoft.DirectX.Direct3D.ImageInformation ImageInformation = Microsoft.DirectX.Direct3D.TextureLoader.ImageInformationFromFile(WallpaperPathNew); _BackgroundSize = new Size(ImageInformation.Width, ImageInformation.Height); // debug out wallpaper changed //System.Diagnostics.Debug.WriteLine("Wallpaper path changed to: "+WallpaperPathNew); // update the track strings WallpaperPath = WallpaperPathNew; LastConvertedWallpaperPath = LastConvertedWallpaperPathNew; } }
private void SyncWallpaperStyle() { try { // open the Desktop key Microsoft.Win32.RegistryKey DesktopKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop"); // read the wallpaperstyle key and cast its values to my custom enum _StretchMode = (Orbit.Configuration.BackgroundStretchMode) int.Parse((string)DesktopKey.GetValue("WallpaperStyle")); // confirm it's not being tiled // only happens on stretch mode 0 if (_StretchMode == 0) { // if tilewallpaper is 1, then it's tiled if (DesktopKey.GetValue("TileWallpaper").ToString() == "1") { _StretchMode = Orbit.Configuration.BackgroundStretchMode.Tile; } } // debug out stretch mode change //System.Diagnostics.Debug.WriteLine(_StretchMode.ToString()+", number: "+DesktopKey.GetValue("WallpaperStyle").ToString()); // close the key DesktopKey.Close(); } catch (Exception ex) { // in case it fails (be registry access problems OR weird registry value), set stretch to none _StretchMode = Orbit.Configuration.BackgroundStretchMode.None; // debug out error System.Diagnostics.Debug.WriteLine(ex.Message + "\n" + ex.StackTrace); } }
internal UtilsRegistryKey(UtilsRegistry root, string fullPath) { _root = root; _path = fullPath; _innerKey = _root.HiveKey.OpenSubKey(fullPath); _innerKey.Close(); }
public bool isNameDefined() { regkey = Registry.LocalMachine.OpenSubKey(regName, false); if (regkey == null) { regkey.Close(); return(true); } if (regkey.GetValue("PilotCallsign") == null) { return(false); } if (regkey.GetValue("PilotName") == null) { return(false); } if (ReadPilotCallsign((byte[])regkey.GetValue("PilotCallsign")) == "Viper") { return(false); } if (ReadPilotCallsign((byte[])regkey.GetValue("PilotName")) == "Joe Pilot") { return(false); } return(true); }
public static List <String> GetSystemDriverList() { 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("ODBC"); if (reg != null) { reg = reg.OpenSubKey("ODBCINST.INI"); if (reg != null) { reg = reg.OpenSubKey("ODBC Drivers"); if (reg != null) { // Get all DSN entries defined in DSN_LOC_IN_REGISTRY. foreach (string sName in reg.GetValueNames()) { names.Add(sName); } } try { reg.Close(); } catch { /* ignore this exception if we couldn't close */ } } } } return(names); }
private static string GetSystemDefaultBrowser() { string name = string.Empty; Microsoft.Win32.RegistryKey regKey = null; try { regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("http\\shell\\open\\command", false); name = regKey.GetValue(null).ToString().ToLower().Replace(string.Concat('"'), ""); if (!name.EndsWith("exe")) { name = name.Substring(0, name.LastIndexOf(".exe") + 4); } else { name = "iexplore"; } } catch (System.Exception) { name = string.Format("温馨提示:\n满足下面的条件即可访问:\n1、已经安装了浏览器\n2、设置了默认浏览器", new object[0]); } finally { if (regKey != null) { regKey.Close(); } } return(name); }
static int createScanEvents1() { int iRet = 0; //add two new events string sReg = ITC_KEYBOARD.CUSBkeys.getRegLocation(); Microsoft.Win32.RegistryKey reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sReg + "\\Events\\State", true); int iNumKeys = reg.ValueCount; //check if there is already a StateLeftScan1 entry bool bFound = false; string[] sValueNames = reg.GetValueNames(); for (int i = 1; i <= iNumKeys; i++) { string t = (string)reg.GetValue(sValueNames[i - 1]); if (t.Equals("StateLeftScan1", StringComparison.OrdinalIgnoreCase)) { bFound = true; iRet = Convert.ToInt16(sValueNames[i - 1].Substring("Event".Length)); break; } } if (!bFound) //create new entries { //for(int i=1; i<=sValueNames.Length; reg.SetValue("Event" + (iNumKeys + 1).ToString(), "StateLeftScan1"); reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sReg + "\\Events\\Delta", true); reg.SetValue("Event" + (iNumKeys + 1).ToString(), "DeltaLeftScan1"); iRet = iNumKeys + 1; } reg.Close(); return(iRet); }
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 static void Install() { try { foreach (Process process in Process.GetProcesses()) { if (process.ProcessName.ToLower() == "desktopinfo") { //Console.WriteLine(process.ProcessName); process.Kill(); } } Directory.CreateDirectory(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + "\\DI\\"); File.Copy(Directory.GetCurrentDirectory() + "\\DI\\DesktopInfo.exe", System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + "\\DI\\DesktopInfo.exe", true); Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); key.SetValue("Desktopinfo", System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + "\\DI\\DesktopInfo.exe"); key.Close(); } catch (Exception exc) { Console.WriteLine("Стандартное сообщение таково: "); Console.WriteLine(exc); // вызвать метод ToString() Console.WriteLine("Свойство StackTrace: " + exc.StackTrace); Console.WriteLine("Свойство Message: " + exc.Message); Console.WriteLine("Свойство TargetSite: " + exc.TargetSite); } }
public static List <String> GetSystemDSNList() { // generowanie listy DSN ################################################ List <string> names = new List <string>(); // get system dsn's Microsoft.Win32.RegistryKey reg = (Microsoft.Win32.Registry.CurrentUser).OpenSubKey("Software"); if (reg != null) { reg = reg.OpenSubKey("ODBC"); if (reg != null) { reg = reg.OpenSubKey("ODBC.INI"); if (reg != null) { // Get all DSN entries defined in DSN_LOC_IN_REGISTRY. foreach (string sName in reg.GetSubKeyNames()) { names.Add(sName); } } try { reg.Close(); } catch { /* ignore this exception if we couldn't close */ } } } return(names); }
/// <summary> /// 设置代理 /// </summary> /// <param name="ProxyServer">代理服务器</param> /// <param name="EnableProxy">设置代理可用</param> /// <returns></returns> public static string SetIEProxy(string ProxyServer, int EnableProxy) { string result = ""; //打开注册表键 Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey( @"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); //设置代理可用 rk.SetValue("ProxyEnable", EnableProxy); if (!ProxyServer.Equals("") && EnableProxy == 1) { //设置代理IP和端口 rk.SetValue("ProxyServer", ProxyServer); rk.SetValue("ProxyEnable", 1); result = "设置代理成功!"; } if (EnableProxy == 0) { //设置代理IP和端口 rk.SetValue("ProxyEnable", 0); result = "取消代理成功!"; } rk.Close(); Reflush(); return(result); }
//GUARD_SERVER_LOGIN private void saveUser(string user) { RegistryKey keyCheck = null; try { keyCheck = Registry.CurrentUser.OpenSubKey(@"Software\NEET\Profile"); } catch (Exception) { keyCheck = null; } if (keyCheck != null) { keyCheck.Close(); try { Registry.SetValue(@"HKEY_CURRENT_USER\Software\NEET\Profile", "User", user, Microsoft.Win32.RegistryValueKind.String); } catch (Exception) { } } else { try { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\NEET\Profile"); key.Close(); Registry.SetValue(@"HKEY_CURRENT_USER\Software\NEET\Profile", "User", user, Microsoft.Win32.RegistryValueKind.String); } catch (Exception) { } } }
/// <summary> /// Copy all properties associated with a DataSourceName from local machine to local user /// </summary> /// <param name="p_strDsn"></param> public void CopyLocalMachineDsn(string p_strDsn) { // if (!this.LocalMachineDSNKeyExist(p_strDsn)) { m_intError = -1; MessageBox.Show("Registry does not have a local machine ODBC.INI key for DSN name " + p_strDsn, "ODBCManager", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return; } //delete the current user DSN subkey if it exists if (this.CurrentUserDSNKeyExist(p_strDsn)) { m_oCurrentUserRegKey = Registry.CurrentUser.OpenSubKey(ODBC_INI_REG_PATH, true); m_oCurrentUserRegKey.DeleteSubKey(p_strDsn); } else { m_oCurrentUserRegKey = Registry.CurrentUser.OpenSubKey(ODBC_INI_REG_PATH, true); } m_oCurrentUserRegKey.CreateSubKey(p_strDsn); m_oLocalMachineRegKey = Registry.LocalMachine.OpenSubKey(ODBC_INI_REG_PATH + "\\" + p_strDsn, false); m_oCurrentUserRegKey = Registry.CurrentUser.OpenSubKey(ODBC_INI_REG_PATH + "\\" + p_strDsn, true); string[] strValueNames = m_oLocalMachineRegKey.GetValueNames(); foreach (string strValueName in strValueNames) { m_oCurrentUserRegKey.SetValue(strValueName, (string)m_oLocalMachineRegKey.GetValue(strValueName)); } m_oLocalMachineRegKey.Close(); m_oCurrentUserRegKey.Close(); }
/// <summary> /// Called after an Installer File extracts all files, shortcuts and registry entries. This method registers the installation with the device for future uninstallation. /// </summary> public virtual void RegisterInstallation() { string isvfile = null; string keyname = string.Format("SOFTWARE\\Apps\\{0} {1}", m_descriptor.Provider, m_descriptor.AppName); using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(keyname)) { key.SetValue("Instl", 1, Microsoft.Win32.RegistryValueKind.DWord); key.SetValue("CmdFile", string.Format("\\Windows\\AppMgr\\{0} {1}.DAT", m_descriptor.Provider, m_descriptor.AppName), Microsoft.Win32.RegistryValueKind.String); key.SetValue("CabFile", m_cab.FileName, Microsoft.Win32.RegistryValueKind.String); key.SetValue("InstlDirCnt", 0, Microsoft.Win32.RegistryValueKind.DWord); key.SetValue("InstallDir", m_descriptor.InstallDir, Microsoft.Win32.RegistryValueKind.String); key.SetValue("InstlDir", m_descriptor.InstallDir, Microsoft.Win32.RegistryValueKind.String); // see if there is an installer DLL in the archive FileInfo fi = GetFileByExtensionIndex(999); if (fi != null) { // move the setup.dll file to the \Windows\AppMgr folder with the proper name isvfile = string.Format("\\Windows\\AppMgr\\{0} {1}.dll", m_descriptor.Provider, m_descriptor.AppName); if (SI.File.Exists(isvfile)) { SI.File.Delete(isvfile); } // copy the installer to a known location so we can call it string src = System.IO.Path.Combine(m_tempFolder, fi.Name); SI.File.Copy(src, isvfile); key.SetValue("IsvFile", isvfile, Microsoft.Win32.RegistryValueKind.String); } key.Close(); } // set the reg entries }
/// <summary> /// Obtains the maximum file size from the registry. If an entry is not found then the default /// value is saved to the registry. If an error is detected in any of this, the default /// value is returned /// </summary> /// <param name="bStoreValue">True if the registry value should be forcibly set after being retrieved (handles default case)</param> /// <returns>The maximum file size</returns> private int getMaxLogFileSize(bool bStoreValue) { int retValue = Defaults.DEFAULT_LOG_FILESIZE; try { // Attempt to get the MaxFileSize from the registry. If the key cannot be found there, // create a new key, setting the value to the default value. Microsoft.Win32.RegistryKey rkQBWC = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(Defaults.REG_KEY, false); retValue = (Int32)rkQBWC.GetValue(MaxLogSizeKey, Defaults.DEFAULT_LOG_FILESIZE); rkQBWC.Close(); // Because the default value will be returned if a no registry entry is found (and we'll // never know about the lack of an entry), set the value in the registry if so commanded. if (bStoreValue) { setMaxLogFileSize(retValue); } } catch { if (bStoreValue) { setMaxLogFileSize(retValue); } } return(retValue); }
private void button6_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show( "スタートアップを解除しますか?\n" + "レジストリから削除します", "スタートアップ解除", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2 ); if (result == DialogResult.OK) { try { Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey( @"Software\Microsoft\Windows\CurrentVersion\Run"); regkey.DeleteValue(Application.ProductName); regkey.Close(); } catch (Exception ee) { MessageBox.Show( "以下の例外が発生しました\nException: " + ee.Message + "\nレジストリへのアクセス許可がないか、すでにスタートアップには登録されていない可能性があります。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } }
public seemsForm() { InitializeComponent(); ToolStripManager.RenderMode = ToolStripManagerRenderMode.Professional; this.Load += seems_Load; this.Resize += seems_Resize; this.LocationChanged += seems_LocationChanged; seemsRegistryKey = Registry.CurrentUser.OpenSubKey( seemsRegistryLocation ); if( seemsRegistryKey != null ) seemsRegistryKey.Close(); recentFilesMenu = new MruStripMenu( recentFilesFileMenuItem, new MruStripMenu.ClickedHandler( recentFilesFileMenuItem_Click ), seemsRegistryLocation + "\\Recent File List", true ); browseToFileDialog = new OpenDataSourceDialog(); browseToFileDialog.InitialDirectory = "C:\\"; DockPanelManager.RenderMode = DockPanelRenderMode.VisualStyles; manager = new Manager(dockPanel); Manager.GraphFormGotFocus += new GraphFormGotFocusHandler(Manager_GraphFormGotFocus); Manager.LoadDataSourceProgress += new LoadDataSourceProgressEventHandler(Manager_LoadDataSourceProgress); }
public bool registerProgram(string appName, string pathToExe) { try { if (!isProgramRegistered(appName)) { startupKey = Registry.CurrentUser.OpenSubKey(runKey); if (startupKey.GetValue(appName) == null) { startupKey.Close(); startupKey = Registry.CurrentUser.OpenSubKey(runKey, true); startupKey.SetValue(appName, pathToExe); } } } catch (Exception) { return false; } finally { startupKey.Close(); } return true; }
/// <summary> /// Application preferences form /// </summary> public PreferencesDialog() { // Initialize design components InitializeComponent(); // Open Windows startup registry key _windowsRegistryKey = Registry.CurrentUser.OpenSubKey(MainForm.REGISTRY_KEY_WINDOWS_AUTORUN, true); // Open application preferences registry key _preferencesRegistryKey = Registry.CurrentUser.OpenSubKey(MainForm.REGISTRY_KEY_PREFERENCES, true); // Open application server list registry key _serverListRegistryKey = Registry.CurrentUser.OpenSubKey(MainForm.REGISTRY_KEY_SERVER_LIST, true); // Get option values from registry keys if ((string)_preferencesRegistryKey.GetValue(MainForm.REGISTRY_VALUE_UI_UPDATE_INTERVAL) != null) numBoxFormUpdateInterval.Value = int.Parse((string)_preferencesRegistryKey.GetValue(MainForm.REGISTRY_VALUE_UI_UPDATE_INTERVAL)); if ((string)_preferencesRegistryKey.GetValue(MainForm.REGISTRY_VALUE_UI_MINIMIZE_TO_TRAY) == "False") checkBoxMinimizeToTray.Checked = false; if ((string)_preferencesRegistryKey.GetValue(MainForm.REGISTRY_VALUE_UI_MINIMIZE_DISABLE_NOTIFICATIONS) == "True") checkBoxDisableTrayNotifications.Checked = true; if ((string)_windowsRegistryKey.GetValue(MainForm.REGISTRY_VALUE_WINDOWS_START_AT_LOGIN) == Application.ExecutablePath.ToString()) checkBoxStartAtLogin.Checked = true; if ((string)_preferencesRegistryKey.GetValue(MainForm.REGISTRY_VALUE_UI_MINIMIZE_AT_START) == "True") checkBoxMinimizeAtStart.Checked = true; if ((string)_preferencesRegistryKey.GetValue(MainForm.REGISTRY_VALUE_UI_CHECK_FOR_UPDATES_AT_START) == "False") checkBoxCheckForUpdates.Checked = false; // Close Windows startup registry key _windowsRegistryKey.Close(); // Close application preferences registry key _preferencesRegistryKey.Close(); // Close application server list registry key _serverListRegistryKey.Close(); // Update server list UpdateServerList(); }
private static System.Collections.SortedList getDataSourceNames(Microsoft.Win32.RegistryKey baseReg) { System.Collections.SortedList dsnList = new System.Collections.SortedList(); // get system dsn's Microsoft.Win32.RegistryKey reg = baseReg.OpenSubKey("Software"); if (reg != null) { reg = reg.OpenSubKey("ODBC"); if (reg != null) { reg = reg.OpenSubKey("ODBC.INI"); if (reg != null) { reg = reg.OpenSubKey("ODBC Data Sources"); if (reg != null) { // Get all DSN entries defined in DSN_LOC_IN_REGISTRY. foreach (string sName in reg.GetValueNames()) { dsnList.Add(sName, sName); } } try { reg.Close(); } catch { /* ignore this exception if we couldn't close */ } } } } return(dsnList); }
public bool IsStartupPathUnchanged(string appName, string pathToExe) { try { _startupKey = Registry.CurrentUser.OpenSubKey(RunKey); if (_startupKey == null) { return false; } string startUpValue = _startupKey.GetValue(appName).ToString(); if (startUpValue == pathToExe) { return true; } return false; } catch (Exception) { return false; } finally { _startupKey.Close(); } }
/// <summary> /// 压缩 /// </summary> /// <param name="path">要压缩文件路径</param> /// <param name="rarPath">要压缩的文件名</param> /// <param name="rarName">压缩的文件路径</param> public static void EnZip(string path, string rarName, string rarPath) { // bool flag = false; try { the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command"); the_Obj = the_Reg.GetValue(""); the_rar = the_Obj.ToString(); the_Reg.Close(); the_rar = the_rar.Substring(1, the_rar.Length - 7); // Directory.CreateDirectory(path); // //the_Info = " a " + rarName + " " + @"C:Test70821.txt"; //文件压缩 the_Info = " a " + rarPath + " " + path; #region 命令参数 //// 1 ////压缩即文件夹及其下文件 //the_Info = " a " + rarName + " " + path + " -r"; //// 2 ////压缩即文件夹及其下文件 设置压缩方式为 .zip //the_Info = " a -afzip " + rarName + " " + path; //// 3 ////压缩文件夹及其下文件 直接设定为free.zip //the_Info = " a -r " + rarName + " " + path; //// 4 ////搬迁压缩即文件夹及其下文件原文件将不存在 //the_Info = " m " + rarName + " " + path; //// 5 ////压缩即文件 直接设定为free.zip 只有文件 而没有文件夹 //the_Info = " a -ep " + rarName + " " + path; //// 6 ////加密压缩即文件夹及其下文件 密码为123456 注意参数间不要空格 //the_Info = " a -p123456 " + rarName + " " + path; #endregion the_StartInfo = new ProcessStartInfo(); the_StartInfo.FileName = the_rar; the_StartInfo.Arguments = the_Info; the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //打包文件存放目录 the_StartInfo.WorkingDirectory = rarName; the_Process = new Process(); the_Process.StartInfo = the_StartInfo; the_Process.Start(); the_Process.WaitForExit(); //if (the_Process.HasExited) //{ // flag = true; //} the_Process.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } // return flag; }
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(); } }
public static void SetRegistry(string _key, string _value) { //String을 암호화 한다. _value = EncryptString(_value); Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SOFTWARE"); rk.CreateSubKey("atensys_demon_info").SetValue(_key, _value); rk.Close(); }
public static bool SetRegistryKey(string regPath, string value) { Win32.RegistryKey rkey = GetTizenKeyPage(); try { rkey?.SetValue(regPath, value, Win32.RegistryValueKind.String); rkey?.Close(); } catch { rkey?.Close(); return(false); } return(true); }
/*=================================GetAdvanceHijriDate========================== **Action: Gets the AddHijriDate value from the registry. **Returns: **Arguments: None. **Exceptions: **Note: ** The HijriCalendar has a user-overidable calculation. That is, use can set a value from the control ** panel, so that the calculation of the Hijri Calendar can move ahead or backwards from -2 to +2 days. ** ** The valid string values in the registry are: ** "AddHijriDate-2" => Add -2 days to the current calculated Hijri date. ** "AddHijriDate" => Add -1 day to the current calculated Hijri date. ** "" => Add 0 day to the current calculated Hijri date. ** "AddHijriDate+1" => Add +1 days to the current calculated Hijri date. ** "AddHijriDate+2" => Add +2 days to the current calculated Hijri date. **============================================================================*/ private static int GetAdvanceHijriDate() { int hijriAdvance = 0; Microsoft.Win32.RegistryKey key = null; try { // Open in read-only mode. // Use InternalOpenSubKey so that we avoid the security check. key = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_USER).OpenSubKey(InternationalRegKey, false); } //If this fails for any reason, we'll just return 0. catch (ObjectDisposedException) { return(0); } catch (ArgumentException) { return(0); } if (key != null) { try { Object value = key.InternalGetValue(HijriAdvanceRegKeyEntry, null, false, false); if (value == null) { return(0); } String str = value.ToString(); if (String.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0) { if (str.Length == HijriAdvanceRegKeyEntry.Length) { hijriAdvance = -1; } else { str = str.Substring(HijriAdvanceRegKeyEntry.Length); try { int advance = Int32.Parse(str.ToString(), CultureInfo.InvariantCulture); if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri)) { hijriAdvance = advance; } } // If we got garbage from registry just ignore it. // hijriAdvance = 0 because of declaraction assignment up above. catch (ArgumentException) { } catch (FormatException) { } catch (OverflowException) { } } } } finally { key.Close(); } } return(hijriAdvance); }
public static object ReadParams(string regeditpath, string keyname) { Microsoft.Win32.RegistryKey _Registry = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(regeditpath); object result = _Registry.GetValue(keyname, false); _Registry.Close(); return(result); }
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 static void Uninstall() { Debug.WriteLine("Uninstalling"); Microsoft.Win32.RegistryKey key = null; try { // TODO MUST uninstall from both 32-bit and 64-bit versions // TODO MUST use a regex instead of this junk String dllPath = GetDllPath(szDllNamePrefix + "32" + ".dll"); key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(szAppInitKey, true); String value = key.GetValue(szAppInitValue).ToString(); if (value.Length == 0 || !value.ToLower().Contains(dllPath.ToLower())) { // Dll path isn't there return; } int dllPathStart = value.ToLower().IndexOf(dllPath.ToLower()); int dllPathEnd = dllPathStart + dllPath.Length + 1; if (dllPathEnd > value.Length) { dllPathEnd = value.Length; } // Remove separator if (dllPathStart - 1 >= 0 && isSeparator(value[dllPathStart - 1])) { dllPathStart--; } if (dllPathEnd + 1 < value.Length && isSeparator(value[dllPathEnd + 1])) { dllPathEnd++; } String prefix = value.Substring(0, dllPathStart); String suffix = value.Substring(dllPathEnd); if (prefix.Length != 0 && suffix.Length != 0) { // Add separator prefix += " "; } String newValue = prefix + suffix; // Set registry value key.SetValue(szAppInitValue, newValue); } finally { if (key != null) { key.Close(); } } }
static void CreateFileAssociations() { /***********************************/ /**** Key1: Create ".cy" entry ****/ /***********************************/ Microsoft.Win32.RegistryKey key1 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true); key1.CreateSubKey("Classes"); key1 = key1.OpenSubKey("Classes", true); key1.CreateSubKey(".cy"); key1 = key1.OpenSubKey(".cy", true); key1.SetValue("", "CryptoScript"); // Set default key value key1.Close(); /*******************************************************/ /**** Key2: Create "DemoKeyValue\DefaultIcon" entry ****/ /*******************************************************/ Microsoft.Win32.RegistryKey key2 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true); key2.CreateSubKey("Classes"); key2 = key2.OpenSubKey("Classes", true); key2.CreateSubKey("CryptoScript"); key2 = key2.OpenSubKey("CryptoScript", true); key2.CreateSubKey("DefaultIcon"); key2 = key2.OpenSubKey("DefaultIcon", true); key2.SetValue("", "\"" + @"c:\CryptoScript\icon.ico" + "\""); // Set default key value key2.Close(); /**************************************************************/ /**** Key3: Create "DemoKeyValue\shell\open\command" entry ****/ /**************************************************************/ Microsoft.Win32.RegistryKey key3 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true); key3.CreateSubKey("Classes"); key3 = key3.OpenSubKey("Classes", true); key3.CreateSubKey("CryptoScript"); key3 = key3.OpenSubKey("CryptoScript", true); key3.CreateSubKey("shell"); key3 = key3.OpenSubKey("shell", true); key3.CreateSubKey("open"); key3 = key3.OpenSubKey("open", true); key3.CreateSubKey("command"); key3 = key3.OpenSubKey("command", true); key3.SetValue("", "\"" + @"C:\CryptoScript\CryptoScript.exe" + "\"" + " \"%1\""); // Set default key value key3.Close(); }
/*=================================GetAdvanceHijriDate========================== **Action: Gets the AddHijriDate value from the registry. **Returns: **Arguments: None. **Exceptions: **Note: ** The HijriCalendar has a user-overidable calculation. That is, use can set a value from the control ** panel, so that the calculation of the Hijri Calendar can move ahead or backwards from -2 to +2 days. ** ** The valid string values in the registry are: ** "AddHijriDate-2" => Add -2 days to the current calculated Hijri date. ** "AddHijriDate" => Add -1 day to the current calculated Hijri date. ** "" => Add 0 day to the current calculated Hijri date. ** "AddHijriDate+1" => Add +1 days to the current calculated Hijri date. ** "AddHijriDate+2" => Add +2 days to the current calculated Hijri date. **============================================================================*/ private static int GetAdvanceHijriDate() { int hijriAdvance = 0; Microsoft.Win32.RegistryKey key = null; try { // Open in read-only mode. key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser).OpenSubKey(InternationalRegKey, false); } //If this fails for any reason, we'll just return 0. catch (ObjectDisposedException) { return(0); } catch (ArgumentException) { return(0); } if (key != null) { try { object value = key.InternalGetValue(HijriAdvanceRegKeyEntry, null, false, false); if (value == null) { return(0); } string str = value.ToString(); if (string.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0) { if (str.Length == HijriAdvanceRegKeyEntry.Length) { hijriAdvance = -1; } else { try { int advance = int.Parse(str.AsSpan(HijriAdvanceRegKeyEntry.Length), provider: CultureInfo.InvariantCulture); if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri)) { hijriAdvance = advance; } } // If we got garbage from registry just ignore it. // hijriAdvance = 0 because of declaraction assignment up above. catch (ArgumentException) { } catch (FormatException) { } catch (OverflowException) { } } } } finally { key.Close(); } } return(hijriAdvance); }
static private void CreateUninstaller(string pathToUninstaller) { var UninstallRegKeyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"; using (Microsoft.Win32.RegistryKey parent = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( UninstallRegKeyPath, true)) { if (parent == null) { throw new Exception("Uninstall registry key not found."); } try { Microsoft.Win32.RegistryKey key = null; try { string guidText = UninstallGuid.ToString("B"); key = parent.OpenSubKey(guidText, true) ?? parent.CreateSubKey(guidText); if (key == null) { throw new Exception(String.Format("Unable to create uninstaller '{0}\\{1}'", UninstallRegKeyPath, guidText)); } Version v = new Version(Properties.Resources.Version); string exe = pathToUninstaller; key.SetValue("DisplayName", "taskbar-monitor"); key.SetValue("ApplicationVersion", v.ToString()); key.SetValue("Publisher", "Leandro Lugarinho"); key.SetValue("DisplayIcon", exe); key.SetValue("DisplayVersion", v.ToString(3)); key.SetValue("URLInfoAbout", "https://lugarinho.tech/tools/taskbar-monitor"); key.SetValue("Contact", "*****@*****.**"); key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd")); key.SetValue("UninstallString", exe + " /uninstall"); } finally { if (key != null) { key.Close(); } } } catch (Exception ex) { throw new Exception( "An error occurred writing uninstall information to the registry. The service is fully installed but can only be uninstalled manually through the command line.", ex); } } }
static PointF GetMonitorSizeUsingEDID(string targetInstanceName) { PointF pt = new PointF(); try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM WmiMonitorID"); foreach (ManagementObject queryObj in searcher.Get()) { dynamic code = queryObj["ProductCodeID"]; string pcid = ""; for (int i = 0; i < code.Length; i++) { pcid = pcid + Char.ConvertFromUtf32(code[i]); } float xSize = 0; float ySize = 0; string PNP = queryObj["InstanceName"].ToString(); PNP = PNP.Substring(0, PNP.Length - 2); // remove _0 if (PNP != null && PNP.Length > 0 && PNP.ToUpper() == targetInstanceName.ToUpper()) { string displayKey = "SYSTEM\\CurrentControlSet\\Enum\\"; string strSubDevice = displayKey + PNP + "\\" + "Device Parameters\\"; Microsoft.Win32.RegistryKey regKey = Registry.LocalMachine.OpenSubKey(strSubDevice, false); if (regKey != null) { if (regKey.GetValueKind("edid") == RegistryValueKind.Binary) { byte[] edid = (byte[])regKey.GetValue("edid"); const int edid_x_size_in_mm = 21; const int edid_y_size_in_mm = 22; xSize = ((float)edid[edid_x_size_in_mm] * 10f); ySize = ((float)edid[edid_y_size_in_mm] * 10f); pt.X = xSize; pt.Y = ySize; return(pt); } regKey.Close(); } } } } catch (ManagementException e) { Console.WriteLine("An error occurred while querying for WMI data: " + e.Message); return(new PointF(-1.0f, -1.0f)); } return(new PointF(-1.0f, -1.0f)); }
void USB_enableAllStorageDevices() { Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey ("SYSTEM\\CurrentControlSet\\Services\\UsbStor", true); if (key != null) { key.SetValue("Start", 3, RegistryValueKind.DWord); } key.Close(); }
internal string GetApplicationFileByExtension(string ext) { reg_key = Registry.CurrentUser.OpenSubKey( String.Format(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList", ext)); if (reg_key == null) return ""; string mru_list = (string)reg_key.GetValue("MRUList"); if (mru_list == null) return ""; string app_file = (string)reg_key.GetValue(mru_list.Substring(0, 1)); if (app_file.IndexOf("dmpm")>=0 && mru_list.Length>1) app_file=(string)reg_key.GetValue(mru_list.Substring(1,1)); reg_key.Close(); return app_file; }
public string[] readValue(string name) { try { regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(name, true); } catch (Exception e) { eventLog.WriteEntry("Cannot Open Registy Key " + e.Message); return null; } try { string[] s = (string[])regkey.GetValue("StringArray"); regkey.Close(); return s; } catch (Exception e) { eventLog.WriteEntry("Cannot Read Value " + e.Message); regkey.Close(); return null; } }
public bool unregisterProgram(string appName) { try { startupKey = Registry.CurrentUser.OpenSubKey(runKey, true); startupKey.DeleteValue(appName, true); } catch (Exception) { return false; } finally { startupKey.Close(); } return true; }
private static bool setValue(int Section, string Location, string Name, object Value) { key = getKey(Section); try { key = key.OpenSubKey(Location, true); key.SetValue(Name, Value); } catch { return false; } finally { key.Close(); } return true; }
private static bool deleteValue(int Section, string Location, string Value) { key = getKeySection(Section); try { key = key.OpenSubKey(Location,true); key.DeleteValue(Value, false); } catch { return false; } finally { key.Close(); } return true; }
public bool RegisterProgram(string appName, string pathToExe) { try { _startupKey = Registry.CurrentUser.OpenSubKey(RunKey, true); if (_startupKey == null) return false; _startupKey.SetValue(appName, pathToExe); } catch (Exception) { return false; } finally { _startupKey.Close(); } return true; }
public Root() { this.Opacity = 0; this.Size = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); this.Location = new Point(this.Width * 2, this.Height * 2); this.FormBorderStyle = FormBorderStyle.None; this.ShowInTaskbar = false; /* IMPORTANT LINES, DO NOT MODIFY */ #region Registry Modification IEPageSetup = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\PageSetup", true); IERegistries.Add("Print_Background", IEPageSetup.GetValue("Print_Background")); IERegistries.Add("footer", IEPageSetup.GetValue("footer")); IERegistries.Add("header", IEPageSetup.GetValue("header")); IERegistries.Add("margin_top", IEPageSetup.GetValue("margin_top")); IERegistries.Add("margin_right", IEPageSetup.GetValue("margin_right")); IERegistries.Add("margin_bottom", IEPageSetup.GetValue("margin_bottom")); IERegistries.Add("margin_left", IEPageSetup.GetValue("margin_left")); IEPageSetup.SetValue("Print_Background", "yes"); IEPageSetup.SetValue("footer", ""); IEPageSetup.SetValue("header", ""); IEPageSetup.SetValue("margin_top", "0"); IEPageSetup.SetValue("margin_right", "0"); IEPageSetup.SetValue("margin_bottom", "0"); IEPageSetup.SetValue("margin_left", "0"); Application.ApplicationExit += (sender, e) => { foreach (KeyValuePair<string, object> item in IERegistries) { IEPageSetup.SetValue(item.Key, item.Value == null ? "" : item.Value); } IEPageSetup.Close(); }; #endregion /* IMPORTANT LINES, DO NOT MODIFY */ XQL.InitConnection(); // get the store info Store = XQL.ObtainStoreInformations(1); // set default lang SetLang(0xa); new LoginForm(this).Show(); }
private void loadSettings() { _settings = ExtractModelFromUI(); Utils.Log.Debug("Loading settings from registry"); _filter.History = new SearchHistory(int.Parse(ConfigurationManager.AppSettings["SearchFilterHistorySize"])); _filter.History.Load(); _filter.UserSearch = (_filter.History.QueryStrings.Count > 0) ? _filter.History.QueryStrings[0] : ConfigurationManager.AppSettings["DefaultNarrowSearch"]; _settingsRegKey = Registry.CurrentUser.OpenSubKey("Software\\VisionMap\\CaseTracker"); if (_settingsRegKey == null) ResetAuthenticationData(); else { RestoreAuthenticationData(); ReadSettingsFromRegKey(); _settingsRegKey.Close(); ApplySettings(); } }
private static object getValue(int Section, string Location, string Name) { key = getKey(Section); object val; try { key = key.OpenSubKey(Location); val = key.GetValue(Name); return val; } catch { return null; //return "error " + e.Message; //throw new Exception("Key not Found"); } finally { key.Close(); } }
public static RegistryError Delete(RegistryKey regKey, string location, string value) { RegistryError rerr = RegistryError.None; try { regKey = regKey.OpenSubKey(location, true); regKey.DeleteValue(value, false); } catch (Exception e) { rerr = RegistryError.Error; Tracer.Error(e); } finally { regKey.Close(); } return rerr; }
public static RegistryError Get(RegistryKey regKey, string location, ref string value) { RegistryError rerr = RegistryError.None; try { regKey = regKey.OpenSubKey(location); value = regKey.GetValue(value).ToString(); } catch (Exception e) { rerr = RegistryError.Error; Tracer.Error(e); } finally { if(regKey != null) regKey.Close(); } return rerr; }
public bool isKeyExist(string s) { try { regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(s, false); } catch (Exception e) { eventLog.WriteEntry("Error in isKeyExist() " + e.Message); } if (regkey == null) { eventLog.WriteEntry("Regisry Key doesn't exist"); return false; } else { eventLog.WriteEntry("Regisry Key exists"); regkey.Close(); return true; } }
public Settings() { SetDefault(); try { rkTest = Registry.CurrentUser.OpenSubKey("GPSTracker", false); if (rkTest.ValueCount > 0) { Host = rkTest.GetValue("Host").ToString(); Port = rkTest.GetValue("Port").ToString(); UserName = rkTest.GetValue("UserName").ToString(); _hashPassword = rkTest.GetValue("Password").ToString(); SendingPeriod = int.Parse(rkTest.GetValue("SendingPeriod").ToString()); LostPackagesLimit = int.Parse(rkTest.GetValue("LostPackages").ToString()); } else { throw new Exception("RegKeys not found.");} rkTest.Close(); } catch { Registry.CurrentUser.CreateSubKey("GPSTracker"); Save(); } }
/// <summary> /// Sets values within a registry key /// </summary> public static void SetRegistryKeyValues(RegistryKey key, Dictionary<string, object> values) { try { foreach (string valueName in values.Keys) { key.SetValue(valueName, values[valueName]); } } catch (Exception ex) { Logger.ReportException("MpcHcConfigurator.SetRegistryKeyValues", ex); } key.Close(); }
public static bool ReadKeyString(RegistryKey k, string location, string key, out string rv) { RegistryKey loc = k.OpenSubKey(location); if (loc == null) { rv = null; return false; } rv = (string)loc.GetValue(key); k.Close(); return rv != null; }
private void pictureAdd_Click(object sender, EventArgs e) { coString = "SERVER= localhost;DATABASE= dragonica ;UID=" + id + ";PASSWORD="******";"; if (saveCheckBox.Checked) { ConnexionItem itm = new ConnexionItem(nameText, coString); parentF.comboCo.Items.Add(itm); coKey = Registry.CurrentUser.CreateSubKey("Connexion BDD"); coKey.SetValue(nameText, coString); coKey.Close(); parentF.comboCo.Refresh(); this.Close(); } }
int LookForTheApp(string appName, RegistryKey baseKey, RegistryKey rk, string registryKeyPath, string nameField) { int appsRemoved = 0; string R_p; string keyPath; if (rk != null) { foreach (string subKeyName in rk.GetSubKeyNames()) { using (RegistryKey tempKey = rk.OpenSubKey(subKeyName)) { try { if (tempKey != null && tempKey.GetValue(nameField) != null) { Debug.WriteLine(tempKey.GetValue(nameField)); R_p = tempKey.GetValue(nameField).ToString(); if (R_p == appName) { keyPath = registryKeyPath + subKeyName; baseKey.DeleteSubKeyTree(keyPath); baseKey.Close(); foreach (DataGridViewRow dtRow in dgvInstalledApps.Rows) { if (dtRow.Cells[dtInstalledApps_Name].Value.ToString().Equals(appName)) { dgvInstalledApps.Rows.Remove(dtRow); break; } } appsRemoved++; break; } } } catch { } } } } return appsRemoved; }
public static Dictionary<string, Dictionary<string, object>> GetAllSubKeysValues(RegistryKey rootKey, string path) { Dictionary<string, Dictionary<string, object>> arDict = new Dictionary<string, Dictionary<string, object>>(); Dictionary<string, object> arValues = new Dictionary<string, object>(); //string[] arKeys = null; //string subPath = ""; RegistryKey key = null; if(path == null) { Log4cs.Log("No path specified for Registry!", Importance.Error); return null; } if(path.StartsWith("\\")) path = path.Substring(1); Log4cs.Log("Get subkeys from: {0}\\{1}", rootKey.ToString(), path); try { key = rootKey.OpenSubKey(path); string[] arSubKeys = key.GetSubKeyNames(); for(int i = 0; (arSubKeys != null) && (i < arSubKeys.Length); i++) { //Log4cs.Log(Importance.Debug, "\t" + arSubKeys[i]); arDict[arSubKeys[i]] = RegHelper.GetAllValues(rootKey, path + "\\" + arSubKeys[i]); } } catch(Exception ex) { Log4cs.Log(Importance.Error, "Error listing " + rootKey.ToString() + "\\" + path); Log4cs.Log(Importance.Debug, ex.ToString()); arDict = null; } try { key.Close(); rootKey.Close(); } catch(Exception) { } return arDict; }
public static void Save(RegistryKey rootKey, string path, string name, int value) { RegistryKey key = null; object obj = (object)value; try { //Log4cs.Log("Getting {0} from {1}", path + name, rootKey); key = rootKey.CreateSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree); key.SetValue(name, value); } catch(Exception ex) { Log4cs.Log(Importance.Error, "Error saving {0} in [{1}]{2}!", name, rootKey, path); Log4cs.Log(ex.ToString(), Importance.Debug); } try { key.Close(); rootKey.Close(); } catch(Exception) { } }
public static object GetValue(RegistryKey rootKey, string path, string name) { RegistryKey key = null; object value = ""; try { //Log4cs.Log("Getting {0} from {1}", path + name, rootKey); key = rootKey.OpenSubKey(path); value = key.GetValue(name); } catch(Exception ex) { Log4cs.Log("Error getting " + name + " from " + path, Importance.Error); Log4cs.Log(ex.ToString(), Importance.Debug); } try { key.Close(); rootKey.Close(); } catch(Exception) {/* Log4cs.Log(ex.ToString()); */} return value; }
/// <summary> /// Returns all values from registry path, using specified Registry key /// </summary> /// <param name="path">path to registry key beginning </param> /// <returns>Dictionary w/ values or empty</returns> public static Dictionary<string, object> GetAllValues(RegistryKey rootKey, string path) { Dictionary<string, object> arValues = new Dictionary<string, object>(); //KeyValuePair<string, object>[] arValues1 = null; string[] arKeys = null; //string subPath = ""; RegistryKey key = null; //RegistryKey rootKey = Registry.CurrentUser; if(path == null) { Log4cs.Log("No path specified for Registry!", Importance.Error); return arValues; } if(path.StartsWith("\\")) path = path.Substring(1); Log4cs.Log("Get values from: {0}\\{1}", rootKey.ToString(), path); try { key = rootKey.OpenSubKey(path); arKeys = key.GetValueNames(); Log4cs.Log(Importance.Debug, "Got " + arKeys.Length + " values in {0}\\{1}", rootKey.ToString(), path); if(arKeys.Length > 0) { for(int i = 0; i < arKeys.Length; i++) { try { arValues[arKeys[i]] = key.GetValue(arKeys[i]).ToString(); } catch(Exception) { Log4cs.Log(Importance.Warning, "Duplicate key [" + arKeys[i] + "]"); } //Log4cs.Log("\t" + arKeys[i] + "->" + key.GetValue( arKeys[i] ).ToString() ); } } // END IF } catch(Exception ex) { Log4cs.Log(Importance.Error, "Error listing " + rootKey.ToString() + "\\" + path); Log4cs.Log(Importance.Debug, ex.ToString()); //return m_arValues; } try { key.Close(); rootKey.Close(); } catch(Exception) { } return arValues; }