C# 操作注册表(三,获取安装软件名和路径2)(转)
原文链接:http://www.cnblogs.com/ustcwhc/archive/2011/11/18/2254367.html
很多软件安装位置不一样,但是他们基本上会在注册表的同一个位置写下自己的名字和程序路径,这个位置就是:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
所以只要去这个地方找软件路径就可以了。当然,有些软件会有自己特定的安装路径,比如:QQ,它就在Tencent下面。
你可以添加你知道的正确的文件名,就是它在注册表中的名字。比如office word在注册表中叫winword
最终拿到的是那个exe的完全路径,如果要文件夹的话就用Path.GetDirectoryName()就行了
View Code
1 public enum Softwares
2 {
3 //The names are the same with the registry names.
4 //You can add any software exists in the "regedit" path:
5 //HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
6
7 EXCEL, //Office Excel
8 WINWORD, //Office Word
9 MSACCESS, //Office Access
10 POWERPNT, //Office PowerPoint
11 OUTLOOK, //Office Outlook
12 INFOPATH, //Office InfoPath
13 MSPUB, //Office Publisher
14 VISIO, //Office Visio
15 IEXPLORE, //IE
16 ITUNES //Apple ITunes
17 //.........
18 }
19
20
21 public static class SoftwareOperator
22 {
23 //When you do not want to use string name, then use the Enum instead
24 public static bool TryGetSoftwarePath(Softwares softName, out string path)
25 {
26 return TryGetSoftwarePath(softName.ToString(), out path);
27 }
28
29 public static bool TryGetSoftwarePath(string softName, out string path)
30 {
31 string strPathResult = string.Empty;
32 string strKeyName = ""; //"(Default)" key, which contains the intalled path
33 object objResult = null;
34
35 Microsoft.Win32.RegistryValueKind regValueKind;
36 Microsoft.Win32.RegistryKey regKey = null;
37 Microsoft.Win32.RegistryKey regSubKey = null;
38
39 try
40 {
41 //Read the key
42 regKey = Microsoft.Win32.Registry.LocalMachine;
43 regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\" + softName.ToString() + ".exe", false);
44
45 //Read the path
46 objResult = regSubKey.GetValue(strKeyName);
47 regValueKind = regSubKey.GetValueKind(strKeyName);
48
49 //Set the path
50 if (regValueKind == Microsoft.Win32.RegistryValueKind.String)
51 {
52 strPathResult = objResult.ToString();
53 }
54 }
55 catch (System.Security.SecurityException ex)
56 {
57 throw new System.Security.SecurityException("You have no right to read the registry!", ex);
58 }
59 catch (Exception ex)
60 {
61 throw new Exception("Reading registry error!", ex);
62 }
63 finally
64 {
65
66 if (regKey != null)
67 {
68 regKey.Close();
69 regKey = null;
70 }
71
72 if (regSubKey != null)
73 {
74 regSubKey.Close();
75 regSubKey = null;
76 }
77 }
78
79 if (strPathResult != string.Empty)
80 {
81 //Found
82 path = strPathResult;
83 return true;
84 }
85 else
86 {
87 //Not found
88 path = null;
89 return false;
90 }
91 }
92 }

浙公网安备 33010602011771号