C#创建读取注册表信息
 View Code
View Code 
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using Microsoft.Win32; 6 7 namespace UlutoraLibs.Utils 8 { 9 public class RegistryUtils 10 { 11 /// <summary> 12 /// 创建注册表信息 13 /// </summary> 14 /// <param name="path">路径</param> 15 /// <param name="name">键名</param> 16 /// <param name="value">键值</param> 17 /// <param name="info">创建信息</param> 18 public static void CreateSubKey(string path, string name, string value, out string info) 19 { 20 RegistryKey rsg = null; 21 info = ""; 22 23 try 24 { 25 if (Registry.LocalMachine.OpenSubKey(path) == null) 26 { 27 Registry.LocalMachine.CreateSubKey(path); 28 } 29 30 rsg = Registry.LocalMachine.OpenSubKey(path, true); 31 rsg.SetValue(name, value); 32 } 33 catch (Exception ex) 34 { 35 info = string.Format("创建注册表信息失败,错误信息{0}", ex.Message); 36 } 37 finally 38 { 39 if (rsg != null) 40 { 41 rsg.Close(); 42 } 43 } 44 } 45 46 /// <summary> 47 /// 根据指定的键名返回键值 48 /// </summary> 49 /// <param name="path">路径</param> 50 /// <param name="name">键名</param> 51 /// <param name="info">读取信息</param> 52 /// <returns>键值</returns> 53 public static string GetValueByName(string path, string name, out string info) 54 { 55 RegistryKey rsg = null; 56 string value = ""; 57 info = ""; 58 59 try 60 { 61 rsg = Registry.LocalMachine.OpenSubKey(path, true); 62 63 if (rsg.GetValue(name) != null) 64 { 65 value = rsg.GetValue(name).ToString(); 66 } 67 } 68 catch (Exception ex) 69 { 70 info = string.Format("读取注册表失败,错误信息{0}", ex.Message); 71 } 72 finally 73 { 74 if (rsg != null) 75 { 76 rsg.Close(); 77 } 78 } 79 80 return value; 81 } 82 } 83 }
调用代码:
 View Code
View Code 
1 info = ""; 2 RegistryUtils.CreateSubKey(Constants.REGISTRY_PATH, Constants.VSS_USERNAME, this.txtVssName.Text, out info); 3 if (!info.Equals("")) 4 { 5 MessageBox.Show(string.Format("保存VSS用户名出错,错误信息:{0}", info), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); 6 return; 7 }
 View Code
View Code 
1 string info = ""; 2 string vssName = RegistryUtils.GetValueByName(Constants.REGISTRY_PATH, Constants.VSS_USERNAME, out info);
 
                     
                    
                 
                    
                 
 
        
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号