Exemplo n.º 1
0
        /// <summary>
        /// 지정된 서브키에서 지정된 이름의 값을 읽어온다.
        /// </summary>
        /// <param name="subKeyName">레지스트리 키 명</param>
        /// <param name="name">이름</param>
        /// <returns>실패시에는 null 값 반환</returns>
        public object GetValue(string subKeyName, string name)
        {
            if (IsDebugEnabled)
            {
                log.Debug("레지스트리에서 값을 읽습니다... subKeyName=[{0}], name=[{1}]", subKeyName, name);
            }

            object value = null;

            if (subKeyName.IsNotWhiteSpace())
            {
                using (RegistryKey subKey = RootKey.CreateSubKey(subKeyName)) {
                    if (subKey != null)
                    {
                        value = subKey.GetValue(name);
                    }
                }
            }

            if (IsDebugEnabled)
            {
                log.Debug("레지스트리에서 값을 읽었습니다!!! subKeyName=[{0}], name=[{1}], value=[{2}]", subKeyName, name, value);
            }

            return(value);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Read specified registry location. Returns data as a byte array
        /// and caller methods can convert to different types.
        /// </summary>
        static private byte[] GetValue(RootKey rootKey, string keyName, string valueName, out int type)
        {
            byte[] data     = null; // data that is returned
            uint   hKey     = 0;    // handle to reg key
            int    dataType = 0;

            try
            {
                // open registry key
                if (WinApi.RegOpenKeyEx((uint)rootKey, keyName, 0, 0, ref hKey) == 0)
                {
                    // get the size of the data
                    int dataSize = 0;
                    WinApi.RegQueryValueEx(hKey, valueName, 0, out dataType, null, ref dataSize);

                    // allocate room for data and read value
                    if (dataSize != 0)
                    {
                        data = new byte[dataSize];
                        WinApi.RegQueryValueEx(hKey, valueName, 0, out dataType, data, ref dataSize);
                    }
                }
            }
            finally
            {
                if (hKey != 0)
                {
                    WinApi.RegCloseKey(hKey);
                }
            }
            // make sure to pass out the datatype for use by calling functions
            type = dataType;
            return(data);
        }
        public void SetRegistryAccess(RootKey rootKey, string pathWithoutRoot)
        {
            WindowsRegistryAccess windowsRegistryAccess = GetAsWindowsRegistryAccess(rootKey, pathWithoutRoot);

            _windowsRegistryWriter.InitializeRegistryAccess(windowsRegistryAccess);
            _windowsRegistryReader.InitializeRegistryAccess(windowsRegistryAccess);
        }
Exemplo n.º 4
0
        internal override void RegisterBrowser()
        {
            //Unregister AppId.
            UnregisterBrowser();

            // Register application.
            var appReg = RootKey.CreateSubKey(string.Format("SOFTWARE\\Clients\\StartMenuInternet\\{0}", AppId));

            appReg.SetValue("", AppName);
            appReg.CreateSubKey("DefaultIcon").SetValue("", AppIcon);
            appReg.CreateSubKey("shell\\open\\command").SetValue("", AppOpenUrlCommand);

            // Install info.
            var appInstallInfo = appReg.CreateSubKey("InstallInfo");

            appInstallInfo.SetValue("IconsVisible", 1);
            appInstallInfo.SetValue("ShowIconsCommand", AppPath); // TOOD: Do I need to support this?
            appInstallInfo.SetValue("HideIconsCommand", AppPath); // TOOD: Do I need to support this?
            appInstallInfo.SetValue("ReinstallCommand", AppReinstallCommand);

            // Register capabilities.
            var capabilityReg = appReg.CreateSubKey("Capabilities");

            capabilityReg.SetValue("ApplicationName", AppName);
            capabilityReg.SetValue("ApplicationIcon", AppIcon);
            capabilityReg.SetValue("ApplicationDescription", AppDescription);

            // Set up protocols we want to handle.
            var urlAssoc = capabilityReg.CreateSubKey("URLAssociations");

            urlAssoc.SetValue("http", AppId);
            urlAssoc.SetValue("https", AppId);
            //urlAssoc.SetValue("ftp", AppID);
        }
Exemplo n.º 5
0
        /// <summary>
        /// 在远程目标机器上创建一个注册表键值
        /// </summary>
        /// <param name="connectionScope">ManagementScope</param>
        /// <param name="machineName">目标机器IP</param>
        /// <param name="BaseKey">注册表分支名</param>
        /// <param name="key">主键名称</param>
        /// <param name="valueName">键值名称</param>
        /// <param name="value">键值</param>
        /// <returns>创建成功则返回0</returns>
        public static int CreateRemoteValue(ManagementScope connectionScope,
                                            string machineName,
                                            RootKey BaseKey,
                                            string key,
                                            string valueName,
                                            string value)
        {
            try
            {
                ObjectGetOptions objectGetOptions = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
                connectionScope.Path = new ManagementPath(@"\\" + machineName + @"\root\DEFAULT:StdRegProv");
                connectionScope.Connect();
                ManagementClass registryTask = new ManagementClass(connectionScope,
                                                                   new ManagementPath(@"DEFAULT:StdRegProv"), objectGetOptions);
                ManagementBaseObject methodParams = registryTask.GetMethodParameters("SetStringValue");

                methodParams["hDefKey"]     = BaseKey;
                methodParams["sSubKeyName"] = key;
                methodParams["sValue"]      = value;
                methodParams["sValueName"]  = valueName;

                ManagementBaseObject exitCode = registryTask.InvokeMethod("SetStringValue",
                                                                          methodParams, null);

                //Wmilog.WriteToLog("in CreateRemoteValue:" + exitCode.ToString());
            }
            catch (ManagementException e)
            {
                //Wmilog.WriteToLog("in CreateRemoteValue(ManagementException):" + e.Message);
                return(-1);
            }
            //Wmilog.WriteToLog("注册表键值写入成功!");
            return(0);
        }
Exemplo n.º 6
0
        public RegistryKey InitializeRegistryKey(WindowsRegistryAccess windowsRegistryAccess)
        {
            _rootKey = windowsRegistryAccess.RootKey;
            _registryKeyInitializer = _implementationFactory.Create <IRegistryKeyInitializer, RegistryAccessAttribute>(IdentifierFunc);

            return(_registryKeyInitializer.InitializeRegistryKey(windowsRegistryAccess));
        }
Exemplo n.º 7
0
        private ChainKey getOrCreateChainKey(SessionState sessionState, ECPublicKey theirEphemeral)

        {
            try
            {
                if (sessionState.hasReceiverChain(theirEphemeral))
                {
                    return(sessionState.getReceiverChainKey(theirEphemeral));
                }
                else
                {
                    RootKey   rootKey      = sessionState.getRootKey();
                    ECKeyPair ourEphemeral = sessionState.getSenderRatchetKeyPair();
                    Pair <RootKey, ChainKey> receiverChain = rootKey.createChain(theirEphemeral, ourEphemeral);
                    ECKeyPair ourNewEphemeral            = Curve.generateKeyPair();
                    Pair <RootKey, ChainKey> senderChain = receiverChain.first().createChain(theirEphemeral, ourNewEphemeral);

                    sessionState.setRootKey(senderChain.first());
                    sessionState.addReceiverChain(theirEphemeral, receiverChain.second());
                    sessionState.setPreviousCounter(Math.Max(sessionState.getSenderChainKey().getIndex() - 1, 0));
                    sessionState.setSenderChain(ourNewEphemeral, senderChain.second());

                    return(receiverChain.second());
                }
            }
            catch (InvalidKeyException e)
            {
                throw new InvalidMessageException(e);
            }
        }
Exemplo n.º 8
0
        static RegistryKey GetRootKey(RootKey rootKey)
        {
            RegistryKey key = null;

            switch (rootKey)
            {
            case RootKey.CurrentUser:
                key = Registry.CurrentUser;
                break;
                //case RootKey.LocalMachine:
                //    key = Registry.LocalMachine;
                //    break;
                //case RootKey.ClassesRoot:
                //    key = Registry.ClassesRoot;
                //    break;
                //case RootKey.PerformanceData:
                //    key = Registry.PerformanceData;
                //    break;
                //case RootKey.CurrentConfig:
                //    key = Registry.CurrentConfig;
                //    break;
                //case RootKey.DynData:
                //    key = Registry.DynData;
                //    break;
                //case RootKey.Users:
                //    key = Registry.Users;
                //    break;
            }
            return(key);
        }
Exemplo n.º 9
0
        public override bool Process()
        {
            string[]      commands = { "exe", "cmd", "bat", "hta", "pif" };
            string        keyPath  = string.Empty;
            RegistryValue value    = null;

            foreach (string command in commands)
            {
                keyPath = "Classes\\" + command + "file\\shell\\open\\command";
                RegistryKey key = RootKey.GetSubkey(keyPath);
                if (null != key)
                {
                    Reporter.Write(keyPath);
                    Reporter.Write("最終更新日時: " + Library.TransrateTimestamp(key.Timestamp, TimeZoneBias, OutputUtc));

                    value = key.GetValue("(Default)");
                    if (null != value)
                    {
                        Reporter.Write("\tCmd: " + value.GetDataAsObject().ToString());
                    }
                    else
                    {
                        Reporter.Write(command + "にはVALUEがありませんでした。");
                    }
                }
                else
                {
                    Reporter.Write(keyPath + " キーは見つかりませんでした。");
                }
            }
            Reporter.Write("");

            return(true);
        }
Exemplo n.º 10
0
        /// <summary>
        /// 在远程目标机器上创建一个注册表主键
        /// </summary>
        /// <param name="connectionScope">ManagementScope</param>
        /// <param name="machineName">目标机器IP</param>
        /// <param name="BaseKey">注册表分支名</param>
        /// <param name="key">主键名称</param>
        /// <returns>创建成功则返回0</returns>
        public static int CreateRemoteKey(ManagementScope connectionScope,
                                          string machineName,
                                          RootKey BaseKey,
                                          string key)
        {
            try
            {
                ObjectGetOptions objectGetOptions = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
                connectionScope.Path = new ManagementPath(@"\\" + machineName + @"\root\DEFAULT:StdRegProv");
                connectionScope.Connect();
                ManagementClass registryTask = new ManagementClass(connectionScope,
                                                                   new ManagementPath(@"DEFAULT:StdRegProv"), objectGetOptions);
                ManagementBaseObject methodParams = registryTask.GetMethodParameters("CreateKey");

                methodParams["hDefKey"]     = BaseKey;
                methodParams["sSubKeyName"] = key;

                ManagementBaseObject exitCode = registryTask.InvokeMethod("CreateKey",
                                                                          methodParams, null);
            }
            catch (ManagementException /*ex*/)
            {
                return(-1);
            }
            return(0);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Deletes a registry value.
        /// </summary>
        /// <param name="rootKey">The root key.</param>
        /// <param name="key">The key.</param>
        /// <param name="valueName">The value name.</param>
        public static void DeleteValue(RootKey rootKey, string key, string valueName)
        {
            RegistryKey askedKey = GetKey(rootKey, key);
            if (askedKey == null) return;

            askedKey.DeleteValue(valueName);
            askedKey.Close();
            askedKey.Flush();
        }
        public WindowsRegistryService(RootKey rootKey, string pathWithoutRoot)
        {
            _registryKeyInitializerFactory = new RegistryKeyInitializerFactory();
            WindowsRegistryAccess windowsRegistryAccess = GetAsWindowsRegistryAccess(rootKey, pathWithoutRoot);

            RegistryKey registryKey = _registryKeyInitializerFactory.InitializeRegistryKey(windowsRegistryAccess);

            _windowsRegistryWriter = new WindowsRegistryWriter(windowsRegistryAccess, registryKey);
            _windowsRegistryReader = new WindowsRegistryReader(windowsRegistryAccess, registryKey);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Returns asked registry value.
        /// </summary>
        /// <param name="rootKey">The root key.</param>
        /// <param name="key">The key.</param>
        /// <param name="valueName">The value name.</param>
        /// <returns>The registry value.</returns>
        public static object GetValue(RootKey rootKey, string key, string valueName)
        {
            RegistryKey askedKey = GetKey(rootKey, key);
            if (askedKey == null) return null;

            object value = askedKey.GetValue(valueName, null);
            askedKey.Close();
            askedKey.Flush();
            return value;
        }
Exemplo n.º 14
0
        public override int GetHashCode()
        {
            int hash = (113 + (11 * RootValue.GetHashCode()) + (17 * RootKey.GetHashCode()) + (31 * subTrees.Count));

            for (int i = 0; i < subTrees.Count; i++)
            {
                hash += ((int)Math.Pow(73, i) * subTrees[i].GetHashCode());
            }

            return(hash);
        }
Exemplo n.º 15
0
 /// <summary>
 /// Forcibly creates this subkey
 /// </summary>
 public void Create()
 {
     if (!Exists())
     {
         if (Root != null)
         {
             Root.Writable = true;
         }
         RootKey.CreateSubKey(name);
         Refresh();
     }
 }
Exemplo n.º 16
0
        public static void Register()
        {
            if (registered)
            {
                return;
            }

            RootKey.Register(FileExtension, ProgId);
            registered = true;

            //// SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
        }
Exemplo n.º 17
0
        /// <summary>
        /// ExtractKeyComponents
        /// </summary>
        /// <param name="key"></param>
        /// <param name="root"></param>
        /// <param name="subkey"></param>
        private static void ExtractKeyComponents(string key, out IntPtr root, out string subkey)
        {
            int firstBack = key.IndexOf(@"\");

            if (firstBack < 1)
            {
                throw (new ArgumentException("key"));
            }
            subkey = key.Substring(firstBack + 1);
            string rootName = key.Substring(0, firstBack);

            root = RootKey.FromString(rootName);
        }
Exemplo n.º 18
0
        /// <summary>
        /// 读取路径为不包含根键的keypath,键名为keyname的注册表键值,缺省返回null
        /// </summary>
        /// <param name="RootKey">根键枚举</param>
        /// <param name="KeyPath">健路径(不含根键)</param>
        /// <param name="KeyName">键名</param>
        /// <returns>读取到的注册表键值</returns>
        public static string GetRegValue(RootKey RootKey, string KeyPath, string KeyName)
        {
            string BackMsg = null;

            try
            {
                RegistryKey Key = RegistryEx(RootKey).OpenSubKey(KeyPath);
                BackMsg = Key.GetValue(KeyName, null).ToString();
            }
            catch (Exception)
            {
            }
            return(BackMsg);
        }
Exemplo n.º 19
0
        /// <summary>
        /// 创建不含根键的路径为regpath的路径
        /// </summary>
        /// <param name="RootKey">根键枚举</param>
        /// <param name="RegPath">要创建的键值路径</param>
        /// <returns></returns>
        public static bool CreateRegPath(RootKey RootKey, string RegPath)
        {
            bool flag = false;

            try
            {
                RegistryEx(RootKey).CreateSubKey(RegPath);
                flag = true;
            }
            catch (Exception)
            {
            }
            return(flag);
        }
Exemplo n.º 20
0
        /// <summary>
        /// 删除路径为SubPath的子项及其附属子项
        /// </summary>
        /// <param name="RootKey">根键枚举</param>
        /// <param name="SubPath">要删除的路径</param>
        /// <returns></returns>
        public static bool DeleteSubKeyTree(RootKey RootKey, string SubPath)
        {
            bool flag = false;

            try
            {
                RegistryEx(RootKey).DeleteSubKeyTree(SubPath);
                flag = true;
            }
            catch (Exception)
            {
            }
            return(flag);
        }
Exemplo n.º 21
0
        private void InitWorldContent()
        {
            //game data
            KeysRoot = new RootKey("root");

            YieldManager = new YieldManagerImpl(new Key(KeysRoot, "yield"));

            WFeatureBiome      = new YieldModifyingSSFR <TerrainBiome>(WorldType.World, new Key(KeysRoot, "tb"), false, TileYieldModifierPriority.Terrain);
            WFeatureVegetation = new YieldModifyingSMFR <TerrainVegetation>(WorldType.World, new Key(KeysRoot, "tv"), TileYieldModifierPriority.Terrain);
            WFeatureLandform   = new YieldModifyingSSFR <TerrainLandform>(WorldType.World, new Key(KeysRoot, "tl"), false, TileYieldModifierPriority.Terrain);

            //civs
            CivilizationManager = new CivilizationManager(new Key(KeysRoot, "civs"), 4);
        }
Exemplo n.º 22
0
        public static void Unregister()
        {
            if (!registered)
            {
                return;
            }

            // In this sample the extension owns the file extension and ProdId, which makes it save to remove
            // it during unregistration. This is often not the case for file extension for application by other vendors.
            // In those cases the file extension and ProdID should not be removed.
            RootKey.Unregister(FileExtension, ProgId);
            registered = false;

            //// SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
        }
Exemplo n.º 23
0
        /// <summary>
        /// 지정된 서브키를 지정된 접근 모드 (읽기, 읽기/쓰기) 로 연다.
        /// </summary>
        /// <param name="subKeyName">서브 키 이름</param>
        /// <param name="writable">true이면 읽기/쓰기여부, false이면 읽기 가능한지 여부</param>
        /// <returns>레지스트리 키 객체</returns>
        public RegistryKey OpenSubKey(string subKeyName, bool writable)
        {
            if (IsDebugEnabled)
            {
                log.Debug("지정된 서브키를 지정된 접근 모드로 연다... subKeyName=[{0}], writable=[{1}]",
                          subKeyName, writable);
            }

            if (subKeyName.IsNotEmpty())
            {
                return(RootKey.OpenSubKey(subKeyName, writable));
            }

            return(null);
        }
Exemplo n.º 24
0
        /// <summary>
        /// 设置路径为不包含根键的keypath,键名为keyname的注册表键值为SetValue,失败返回False
        /// </summary>
        /// <param name="RootKey">根键枚举</param>
        /// <param name="KeyPath">健路径(不含根键)</param>
        /// <param name="KeyName">键名</param>
        /// <param name="KeyValue">键值</param>
        /// <returns></returns>
        public static bool SetRegValue(RootKey RootKey, string KeyPath, string KeyName, object KeyValue)
        {
            bool flag = false;

            try
            {
                RegistryKey Key = RegistryEx(RootKey).OpenSubKey(KeyPath, true);
                Key.SetValue(KeyName, KeyValue);
                flag = true;
            }
            catch (Exception)
            {
            }
            return(flag);
        }
Exemplo n.º 25
0
        public static IView CreateView(IConsole console)
        {
            var root = new RootKey("root");

            YieldManager ym = new YieldManagerImpl(new Key(root, "yield"));
            var          fw = new FeatureWorld(1, ym);

            fw.Lock();

            var world = new TileWorld(fw, 50, 50, WorldMode.Master);
            var view  = new WorldView(console, world);

            view.Renderers.Add(new TestCRenderer());
            return(view);
        }
Exemplo n.º 26
0
        /// <summary>
        /// 删除指定键名的键名
        /// </summary>
        /// <param name="RootKey">根键枚举</param>
        /// <param name="SubPath">路径</param>
        /// <param name="KeyName">键名</param>
        /// <returns></returns>
        public static bool DeleteRegKeyName(RootKey RootKey, string SubPath, string KeyName)
        {
            bool flag = false;

            try
            {
                RegistryKey Key = RegistryEx(RootKey).OpenSubKey(SubPath, true);
                Key.DeleteValue(KeyName);
                flag = true;
            }
            catch (Exception)
            {
            }
            return(flag);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="rootKey"></param>
        /// <param name="reporter"></param>
        /// <param name="logger"></param>
        public ClassBase(RegistryKey rootKey, short timeZoneBias, bool outputUtc, Reporter reporter, Logger logger, string currentControlSet = "")
        {
            if (!string.IsNullOrEmpty(currentControlSet))
            {
                Current = currentControlSet;
            }

            Initialize();

            _rootKey      = rootKey;
            _timeZoneBias = timeZoneBias;
            _outputUtc    = outputUtc;
            _reporter     = reporter;
            _logger       = logger;

            Reporter.Write(Library.GetClassName(this));
            Reporter.Write("キーの説明:" + Description);
            if (!string.IsNullOrEmpty(KeyPath))
            {
                if (PrintKeyInBase)
                {
                    Reporter.Write("キーのパス:" + KeyPath);
                }
                Key = RootKey.GetSubkey(KeyPath);

                if (null != Key)
                {
                    if (PrintKeyInBase)
                    {
                        Reporter.Write("キーの最終更新日時:" + Library.TransrateTimestamp(Key.Timestamp, TimeZoneBias, OutputUtc));
                        Reporter.Write("");
                    }
                }
                else
                {
                    Reporter.Write("");
                    if (!PrintKeyInBase)
                    {
                        Reporter.Write("検索したキーのパス:" + KeyPath);
                    }
                    Reporter.Write("Keyが見つかりませんでした。");
                    Reporter.Write("");
                }
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// 지정된 키의 하위에 있는 모든 Sub Key의 이름을 반환한다.
        /// </summary>
        /// <param name="keyName">키 이름</param>
        /// <returns>성공시 문자열 1차원 배열, 실패시 길이가 0인 문자열 배열을 반환한다.</returns>
        public string[] GetSubKeyNames(string keyName)
        {
            if (IsDebugEnabled)
            {
                log.Debug("지정된 키의 하위에 있는 모든 Sub Key의 이름을 반환한다... keyName=[{0}]", keyName);
            }

            if (keyName.IsNotEmpty())
            {
                using (RegistryKey key = RootKey.OpenSubKey(keyName))
                    if (key != null)
                    {
                        return(key.GetSubKeyNames());
                    }
            }

            return(new string[0]);
        }
Exemplo n.º 29
0
        static public bool DeleteKey(RootKey rootType, string regSubKey)
        {
            RegistryKey rootKey = GetRootKey(rootType);

            try
            {
                rootKey.DeleteSubKeyTree(regSubKey);
            }
            catch (Exception ex)
            {
                Logger.LogError("操作注册表失败!" + ex.ToString());
                return(false);
            }
            finally
            {
                rootKey.Close();
            }
            return(true);
        }
Exemplo n.º 30
0
        /// <summary>
        /// 修改注册表
        /// </summary>
        /// <param name="key">注册表键</param>
        /// <param name="name">项</param>
        /// <param name="value">值</param>
        private void UpdatePortInRegedit(string key, string name, string value)
        {
            RegistryKey RootKey;
            RegistryKey SubKey;

            RootKey = Registry.LocalMachine;
            try
            {
                SubKey = RootKey.OpenSubKey(key, true);
                if (SubKey != null)
                {
                    SubKey.SetValue(name, value);
                }
                SubKey.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\r" + ex.StackTrace);
            }
        }
Exemplo n.º 31
0
        static public String GetValue(RootKey rootType, string regSubKey, string strName)
        {
            String      strValue = "";
            RegistryKey rootKey  = GetRootKey(rootType);

            try
            {
                RegistryKey theKey = rootKey.OpenSubKey(regSubKey, true);
                if (theKey != null)
                {
                    object obj = theKey.GetValue(strName, "");
                    strValue = obj.ToString();
                }
            }
            catch (Exception ex)
            {
                Logger.LogError("操作注册表失败!" + ex.ToString());
            }
            return(strValue);
        }
Exemplo n.º 32
0
        /// <summary>
        /// 注册键值
        /// </summary>
        /// <param name="RootKey">根键名称</param>
        /// <returns></returns>
        private static RegistryKey RegistryEx(RootKey RootKey)
        {
            RegistryKey RegKey = null;

            switch (RootKey)
            {
            case RootKey.ClassesRoot:
                RegKey = Registry.ClassesRoot;
                break;

            case RootKey.CurrentUser:
                RegKey = Registry.CurrentUser;
                break;

            case RootKey.LocalMachine:
                RegKey = Registry.LocalMachine;
                break;

            case RootKey.Users:
                RegKey = Registry.Users;
                break;

            case RootKey.CurrentConfig:
                RegKey = Registry.CurrentConfig;
                break;

            //已过时
            //case RootKey.DynData:
            //    RegKey = Registry.DynData;
            //    break;
            case RootKey.PerformanceData:
                RegKey = Registry.PerformanceData;
                break;

            default:
                RegKey = Registry.CurrentUser;
                break;
            }
            return(RegKey);
        }
Exemplo n.º 33
0
        /// <summary>
        /// Read specified registry location. Returns data as a byte array
        /// and caller methods can convert to different types.
        /// </summary>
        private static byte[] GetValue(RootKey rootKey, string keyName, string valueName, out int type)
        {
            byte[] data = null;	// data that is returned
            uint hKey = 0;		// handle to reg key
            int dataType = 0;
            try
            {
                // open registry key
                if (WinApi.RegOpenKeyEx((uint)rootKey, keyName, 0, 0, ref hKey) == 0)
                {
                    // get the size of the data
                    int dataSize = 0;
                    WinApi.RegQueryValueEx(hKey, valueName, 0, out dataType, null, ref dataSize);

                    // allocate room for data and read value
                    if (dataSize != 0)
                    {
                        data = new byte[dataSize];
                        WinApi.RegQueryValueEx(hKey, valueName, 0, out dataType, data, ref dataSize);
                    }

                }
            }
            finally
            {
                if (hKey != 0)
                    WinApi.RegCloseKey(hKey);
            }
            // make sure to pass out the datatype for use by calling functions
            type = dataType;
            return data;
        }
Exemplo n.º 34
0
        // Enumerate the values of the registry and return them as coma delimited string
        // caller methods can parse
        public static string EnumValues(RootKey rootKey, string keyName, bool Type)
        {
            string names = null;
            uint hKey = 0;

            try
            {
                // open registry key
                if (WinApi.RegOpenKeyEx((uint)rootKey, keyName, 0, 0, ref hKey) == 0)
                {
                    // loop through the enumerations (assume no more than 100 values, to limit the for loop
                    for (int i = 0; i < 100; i++)
                    {
                        // create 255 character buffer
                        string ValueName = new String(' ',255);

                        // initialize the needed variables
                        int ValueSize = 255;
                        int dataType = 0;
                        byte[] data = null;
                        int dataSize = 0;
                        int retval = 0;
                        string keyClass = null;
                        int keyClassSize = 0;
                        FILETIME lastWrite = new FILETIME();

                        // if Type = 0/false, enumerate values
                        // if Type = 1/true, enumerate keys
                        if (!Type)
                        {
                            retval = WinApi.RegEnumValue((uint)hKey, i, ValueName, ref ValueSize, 0, ref dataType, data, ref dataSize);
                        }
                        else
                        {
                            retval = WinApi.RegEnumKeyEx((uint)hKey, i, ValueName, ref ValueSize, 0, keyClass, ref keyClassSize, ref lastWrite);
                        }
                        // check to see if we got anything
                        if (retval == 0 || retval == 87)
                        {
                            // If the values were enumerated, then tag on their data
                            // else just add the name of the key
                            if (!Type)
                            {
                                // read the data and tag onto the name of the value as hex
                                int type = new int();
                                byte[] tempData = GetValue(RootKey.LocalMachine, keyName, ValueName.Substring(0, ValueSize), out type);
                                names += ValueName.Substring(0, ValueSize);

                                // make sure to handle the datatype correctly
                                // for ints display the number, for strings display the converted text
                                switch (type)
                                {
                                    case REG_SZ:
                                        string result = UnicodeEncoding.Unicode.GetString(tempData, 0, tempData.GetLength(0)-1);
                                        names += "(" + result + "),";
                                        break;
                                    case REG_DWORD:
                                        int Num = System.BitConverter.ToInt32(tempData, 0);
                                        names += "(0x" + Num.ToString("X") + ")(d" + Num.ToString() + "),";
                                        //names += "(0x" + Num.ToString("X") + "),";
                                        break;
                                    default:
                                        break;
                                }

                            }
                            else
                            {
                                names += ValueName.Substring(0, ValueSize);
                                names += ",";
                            }

                        }
                        else
                        {
                            // set i to 100 to stop the looping
                            // if retval != 0 then we're done enumerating
                            i = 100;
                        }

                    }
                }
            }
            catch
            {
                // return empty string
                return "";
            }
            // close the key

            if (hKey != 0)
                WinApi.RegCloseKey(hKey);

            return names;
        }
Exemplo n.º 35
0
        /// <summary>
        /// 在远程目标机器上创建一个注册表键值
        /// </summary>
        /// <param name="connectionScope">ManagementScope</param>
        /// <param name="machineName">目标机器IP</param>
        /// <param name="BaseKey">注册表分支名</param>
        /// <param name="key">主键名称</param>
        /// <param name="valueName">键值名称</param>
        /// <param name="value">键值</param>
        /// <returns>创建成功则返回0</returns>
        public static int CreateRemoteValue(ManagementScope connectionScope,
                                    string machineName,
                                    RootKey BaseKey,
                                    string key,
                                    string valueName,
                                    string value)
        {
            try
            {
                ObjectGetOptions objectGetOptions = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
                connectionScope.Path = new ManagementPath(@"\\" + machineName + @"\root\DEFAULT:StdRegProv");
                connectionScope.Connect();
                ManagementClass registryTask = new ManagementClass(connectionScope,
                               new ManagementPath(@"DEFAULT:StdRegProv"), objectGetOptions);
                ManagementBaseObject methodParams = registryTask.GetMethodParameters("SetStringValue");

                methodParams["hDefKey"] = BaseKey;
                methodParams["sSubKeyName"] = key;
                methodParams["sValue"] = value;
                methodParams["sValueName"] = valueName;

                ManagementBaseObject exitCode = registryTask.InvokeMethod("SetStringValue",
                                                                         methodParams, null);

                Wmilog.LogInfoWithLevel("in CreateRemoteValue:" + exitCode.ToString(), Log_LoggingLevel.Admin);
            }
            catch (ManagementException e)
            {
                Wmilog.LogInfoWithLevel("in CreateRemoteValue(ManagementException):" + e.Message, Log_LoggingLevel.Admin);
                return -1;
            }
            Wmilog.LogInfoWithLevel("注册表键值写入成功!", Log_LoggingLevel.Admin);
            return 0;
        }
Exemplo n.º 36
0
        /// <summary>
        /// Checks for a value's existance.
        /// </summary>
        /// <param name="rootKey">The root key.</param>
        /// <param name="key">The key.</param>
        /// <param name="valueName">The value name</param>
        /// <returns>Returns a bool based on asked value's existance.</returns>
        public static bool ValueExists(RootKey rootKey, string key, string valueName)
        {
            RegistryKey askedKey = GetKey(rootKey, key);
            if (askedKey == null) return false;

            object value = askedKey.GetValue(valueName, null);
            askedKey.Close();
            askedKey.Flush();

            return value != null;
        }
Exemplo n.º 37
0
        /* Returns an asked key */
        private static RegistryKey GetKey(RootKey rootKey, string key)
        {
            try
            {
                RegistryKey requestedKey = null;
                RegistryKey registryRoot = null;

                switch (rootKey)
                {
                    case RootKey.HKEY_CLASSES_ROOT: registryRoot = Microsoft.Win32.Registry.ClassesRoot; break;
                    case RootKey.HKEY_CURRENT_USER: registryRoot = Microsoft.Win32.Registry.CurrentUser; break;
                    case RootKey.HKEY_LOCAL_MACHINE: registryRoot = Microsoft.Win32.Registry.LocalMachine; break;
                }

                if (registryRoot != null) requestedKey = registryRoot.OpenSubKey(key, true); // if asked subkey does not exists, the call will just return a null value.
                return requestedKey;
            }
            catch (SecurityException) // Catch any security exceptions which means user may not have appropriate credentals to access the key.
            {
                return null;
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// 在远程目标机器上创建一个注册表主键
        /// </summary>
        /// <param name="connectionScope">ManagementScope</param>
        /// <param name="machineName">目标机器IP</param>
        /// <param name="BaseKey">注册表分支名</param>
        /// <param name="key">主键名称</param>
        /// <returns>创建成功则返回0</returns>
        public static int CreateRemoteKey(ManagementScope connectionScope,
                                  string machineName,
                                  RootKey BaseKey,
                                  string key)
        {
            try
            {
                ObjectGetOptions objectGetOptions = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
                connectionScope.Path = new ManagementPath(@"\\" + machineName + @"\root\DEFAULT:StdRegProv");
                connectionScope.Connect();
                ManagementClass registryTask = new ManagementClass(connectionScope,
                               new ManagementPath(@"DEFAULT:StdRegProv"), objectGetOptions);
                ManagementBaseObject methodParams = registryTask.GetMethodParameters("CreateKey");

                methodParams["hDefKey"] = BaseKey;
                methodParams["sSubKeyName"] = key;

                ManagementBaseObject exitCode = registryTask.InvokeMethod("CreateKey",
                                                                      methodParams, null);

                //Wmilog.WriteToLog("in CreateRemoteKey:" + exitCode.ToString());
            }
            catch (ManagementException e)
            {
                //Wmilog.WriteToLog("in CreateRemoteKey(ManagementException):" + e.Message);
                return -1;
            }
            //Wmilog.WriteToLog("注册表主键创建成功!");
            return 0;
        }
Exemplo n.º 39
0
        /// <summary>
        /// Sets a registry value.
        /// </summary>
        /// <param name="rootKey">The root key.</param>
        /// <param name="key">The key.</param>
        /// <param name="valueName">The value name.</param>
        /// <param name="value">The registry value.</param>
        public static void SetValue(RootKey rootKey, string key, string valueName, object value)
        {
            RegistryKey askedKey = GetKey(rootKey, key);
            if (askedKey == null) return;

            askedKey.SetValue(valueName, value);
            askedKey.Close();
            askedKey.Flush();
        }