我希望获得与文件扩展名相关联的程序的路径,最好是通过Win32 API。
UPD:
假设我的机器上安装了office11和office12,.xls的默认程序是office 11.如果查看HKEY_CLASSES_ROOT \ Excel.Sheet.8 \ shell \ Open \命令,则有一个office11 excel.exe的路径,但是当我右键单击文件时,我可以在“打开方式”菜单项中选择office12。那么这个关联存储在哪里?
我正在使用C#。
感谢。
答案 0 :(得分:12)
我写了一个小例程:
public IEnumerable<string> RecommendedPrograms(string ext)
{
List<string> progs = new List<string>();
string baseKey = @"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\." + ext;
using (RegistryKey rk = Registry.CurrentUser.OpenSubKey(baseKey + @"\OpenWithList"))
{
if (rk != null)
{
string mruList = (string)rk.GetValue("MRUList");
if (mruList != null)
{
foreach (char c in mruList.ToString())
progs.Add(rk.GetValue(c.ToString()).ToString());
}
}
}
using (RegistryKey rk = Registry.CurrentUser.OpenSubKey(baseKey + @"\OpenWithProgids"))
{
if (rk != null)
{
foreach (string item in rk.GetValueNames())
progs.Add(item);
}
//TO DO: Convert ProgID to ProgramName, etc.
}
return progs;
}
这样被调用:
foreach (string prog in RecommendedPrograms("vb"))
{
MessageBox.Show(prog);
}
答案 1 :(得分:3)
曾经想以编程方式将系统上的文件类型与您的应用程序相关联,但是不喜欢自己挖掘注册表的想法?如果是这样,那么这篇文章和代码适合您。
答案 2 :(得分:0)
我改进了 LarsTech 的方法。现在它返回程序的路径。
public List<string> RecommendedPrograms(string ext)
{
//Search programs names:
List<string> names = new List<string>();
string baseKey = @"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\." + ext;
string s;
using (RegistryKey rk = Registry.CurrentUser.OpenSubKey(baseKey + @"\OpenWithList"))
{
if (rk != null)
{
string mruList = (string)rk.GetValue("MRUList");
if (mruList != null)
{
foreach (char c in mruList)
{
s = rk.GetValue(c.ToString()).ToString();
if (s.ToLower().Contains(".exe"))
names.Add(s);
}
}
}
}
if (names.Count == 0)
return names;
//Search paths:
List<string> paths = new List<string>();
baseKey = @"Software\Classes\Applications\{0}\shell\open\command";
foreach (string name in names)
using (RegistryKey rk = Registry.CurrentUser.OpenSubKey(String.Format(baseKey, name)))
{
if (rk != null)
{
s = rk.GetValue("").ToString();
s = s.Substring(1, s.IndexOf("\"", 2) - 1); //remove quotes
paths.Add(s);
}
}
if (paths.Count > 0)
return paths;
//Search pathes for Windows XP:
foreach (string name in names)
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(String.Format(baseKey, name)))
{
if (rk != null)
{
s = rk.GetValue("").ToString();
s = s.Substring(1, s.IndexOf("\"", 2) - 1); //remove quotes
paths.Add(s);
}
}
return paths;
}