2009-02-10 31 views
27

Tôi có thể nhận/đặt giá trị đăng ký bằng cách sử dụng lớp Microsoft.Win32.Registry. Ví dụ:Cách xóa giá trị đăng ký trong C#

Microsoft.Win32.Registry.SetValue(
    @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", 
    "MyApp", 
    Application.ExecutablePath); 

Nhưng tôi không thể xóa bất kỳ giá trị nào. Làm cách nào để xóa giá trị đăng ký?

Trả lời

70

Để xóa giá trị đặt tại câu hỏi của bạn:

string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run"; 
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true)) 
{ 
    if (key == null) 
    { 
     // Key doesn't exist. Do whatever you want to handle 
     // this case 
    } 
    else 
    { 
     key.DeleteValue("MyApp"); 
    } 
} 

Nhìn vào các tài liệu cho Registry.CurrentUser, RegistryKey.OpenSubKeyRegistryKey.DeleteValue để biết thêm.

+1

Làm thế nào tôi có thể xóa toàn bộ thư mục? giả sử tôi muốn xóa '@" Software \ TeamViewer ";' –

10
RegistryKey registrykeyHKLM = Registry.LocalMachine; 
string keyPath = @"Software\Microsoft\Windows\CurrentVersion\Run\MyApp"; 

registrykeyHKLM.DeleteValue(keyPath); 
registrykeyHKLM.Close(); 
+0

mã không hoạt động –

+0

Sửa lỗi, nó sẽ hoạt động ngay bây giờ. –

11

Để xóa tất cả các subkeys/giá trị trong cây (~ đệ quy), đây là một phương pháp mở rộng mà tôi sử dụng:

public static void DeleteSubKeyTree(this RegistryKey key, string subkey, 
    bool throwOnMissingSubKey) 
{ 
    if (!throwOnMissingSubKey && key.OpenSubKey(subkey) == null) { return; } 
    key.DeleteSubKeyTree(subkey); 
} 

Cách sử dụng:

string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run"; 
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true)) 
{ 
    key.DeleteSubKeyTree("MyApp",false); 
} 
+5

Trông giống như một số người làm việc trên .NET, đây cũng là một ý tưởng hay :) Đã được thêm vào cho .NET 4.0 http://msdn.microsoft.com/en-us/library/dd411622.aspx –

Các vấn đề liên quan