阿宽

Nothing is more powerful than habit!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

c# 讀取、更新注冊表

Posted on 2008-04-22 19:50  宽田  阅读(670)  评论(0编辑  收藏  举报
    Asp.net更新客戶端注冊表,會涉及到安全性的問題,所以無法讀取及更新客戶端。這里代碼只能讀取及更新本機電腦注冊表。

using Microsoft.Win32;


    /// <summary>
    
/// 得到電腦名
    
/// </summary>
    string sComputerName = System.Environment.MachineName;
    //注冊表中的路徑「SOFTWARE\CmWeb」
    const string sRegistryPath = @"SOFTWARE\CmWeb";

1、讀取注冊表
    /// <summary>
    
/// 得到注冊表內容
    
/// </summary>
    void GetRegistry()
    {
        
//打開指定路麼的注冊表
        rkKey = Registry.LocalMachine.OpenSubKey(sRegistryPath);
        
if (rkKey != null)
        {
            
//得到注冊表內容
            string sRegistryValue = rkKey.GetValue(sRegistryKey, "").ToString();
        }
    }

2、創建注冊表
    /// <summary>
    
/// 創建注冊表內容
    
/// </summary>
    private void CreateRegistry()
    {
        
//得到「HKEY_LOCAL_MACHINE\SOFTWARE」主鍵
        RegistryKey rkRootKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE",true);
        
if (rkRootKey != null)
        {
            
//不存在CmWeb時創建CmWeb
            if (Array.IndexOf(rkRootKey.GetSubKeyNames(), "CmWeb"< 0)
            {
                rkRootKey.CreateSubKey(
"CmWeb");
            }
            
//得到「HKEY_LOCAL_MACHINE\SOFTWARE\CMWEB」鍵
            rkKey = Registry.LocalMachine.OpenSubKey(sRegistryPath,true);
            
if (rkKey != null)
            {
                
//電腦名
                string sRegValue = sComputerName;

                
//創建鍵值
                rkKey.SetValue(sRegistryKey, sRegValue);
            }
        }
    }

3、更新注冊表

    
/// <summary>
    
/// 更新注冊表
    
/// </summary>
    void UpdateRegistry()
    {
        
//得到「HKEY_LOCAL_MACHINE\SOFTWARE」主鍵
        RegistryKey rkRootKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE",true);
        
if (rkRootKey != null)
        {
            
//不存在「CmWeb」鍵時創建CmWeb
            if (Array.IndexOf(rkRootKey.GetSubKeyNames(), "CmWeb"< 0)
            {
                
//創建鍵名
                rkRootKey.CreateSubKey("CmWeb");
            }
            
//得到「HKEY_LOCAL_MACHINE\SOFTWARE\CMWEB」鍵
            rkKey = Registry.LocalMachine.OpenSubKey(sRegistryPath,true);
            
if (rkKey != null)
            {
                
//電腦名
                string sRegValue = sComputerName;

                
//創建鍵值
                rkKey.SetValue(sRegistryKey, sRegValue);
            }
        }
    }