C#操做註冊表——讀、寫、刪除、判斷等基本操做

1、引入命名空間:spa

using Microsoft.Win32;

 

2、建立註冊表項:CreateSubKey(name)方法code

添加SubKey時候首先要打開一個表項,並設置參數爲true,才能成功建立子項blog

//給要建立的註冊表設置一個變量,使用更方便
private string
RegistFileName = "test";
/// <summary>
/// 建立一個test註冊表項,下面包含OpenLog,和SaveLog兩個子項
/// </summary>
private void CreateRegistFile()
{
  //SOFTWARE在LocalMachine分支下
RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE",true); RegistryKey software = key.CreateSubKey(RegistFileName); RegistryKey test = key.OpenSubKey(RegistFileName,true); RegistryKey Savekey = test.CreateSubKey("SaveLog"); }

 

3、刪除註冊表項:DeleteSubKey(name,true)方法string

RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.OpenSubKey("SOFTWARE", true);
RegistryKey test = software.OpenSubKey(RegistFileName, true);
test.DeleteSubKey("SaveLog",true); 

 

4、添加鍵值:SetValue(name,value)方法it

/// <summary>
/// 將path寫入OPenLog子項
/// </summary>
private void writeToRegistFile(string path)
{
  RegistryKey key
= Registry.LocalMachine;
  RegistryKey software
= key.OpenSubKey("SOFTWARE", true);
  RegistryKey test
= software.OpenSubKey(RegistFileName, true);
  RegistryKey OpenPath = test.OpenSubKey("OpenLog",true);
  //"name"是該鍵值的name,至關於一個別名,可自行設置
  OpenPath.SetValue("name", path); }

 

5、刪除鍵值:DeleteValue(name)方法class

RegistryKey key = Registry.LocalMachine;
RegistryKey software = key.OpenSubKey("SOFTWARE", true);
RegistryKey test = software.OpenSubKey(RegistFileName, true);
RegistryKey OpenPath = test.OpenSubKey("SaveLog",true);
//刪除SaveLog子項下的名爲SaveLog的子鍵
OpenPath.DeleteValue("name");

 

6、判斷註冊表項是否存在:test

/// <summary>
/// 判斷註冊表項是否存在
/// </summary>
/// <returns>bool</returns>
private bool IsRegeditItemExist()
{
  string[] subkeyNames;
  RegistryKey key = Registry.LocalMachine;
  RegistryKey software = key.OpenSubKey("SOFTWARE");
  subkeyNames = software.GetSubKeyNames();
  //在這裏我是判斷test表項是否存在
  foreach (string keyName in subkeyNames)
  {
    if (keyName == RegistFileName)
    {
      key.Close();
      return true;
    }
  }
  key.Close();
  return false;
}

 

7、判斷鍵值是否存在:變量

/// <summary>
/// 判斷該路徑是否已經存在
/// </summary>
/// <param name="path">路徑</param>
/// <returns></returns>
private bool IsRegeditKeyExit(string name)
{string[] saveSubkeyNames;

    RegistryKey key = Registry.LocalMachine;
    RegistryKey software = key.OpenSubKey("SOFTWARE", true);
    RegistryKey test = software.OpenSubKey(RegistFileName, true);
    RegistryKey Savekey = test.OpenSubKey("SaveLog", true);
  //獲取該子項下的全部鍵值的名稱saveSubkeyNames
saveSubkeyNames = Savekey.GetSubKeyNames(); foreach(string keyName in openSubkeyNames) { if(keyName == name) { key.Close(); return false; } } key.Close(); return true; }

 

注:若是沒有該註冊表項或鍵值,則返回的值爲空值,若不經處理運行程序會拋出異常。foreach

有錯誤的地方歡迎指出,謝謝!命名空間

相關文章
相關標籤/搜索