使用所有注册文件类型(而不仅仅是扩展)填充ComboBox的最有效方法是什么
问题描述:
在Windows中用所有注册文件类型填充ComboBox的效率最高?使用所有注册文件类型(而不仅仅是扩展)填充ComboBox的最有效方法是什么
我想要完整的文件类型,而不仅仅是扩展名。我使用VB 9(VS2008)。
谢谢。
答
所有文件类型都存储在注册表中的HKEY_CLASS_ROOT下,您可以使用框架的Registry class获取该文件。
这里的C#代码来执行任务:
using Microsoft.Win32;
public class FileAssoc
{
public string Extension;
public string Filetype;
public FileAssoc(string fileext, string name)
{
Extension = fileext;
Filetype = name;
}
}
public static class EnumRegFiles
{
public static List<FileAssoc> GetFileAssociations()
{
List<FileAssoc> result = new List<FileAssoc>();
RegistryKey rk = Registry.ClassesRoot;
String[] names = rk.GetSubKeyNames();
foreach (string file in names)
{
if (file.StartsWith("."))
{
RegistryKey rkey = rk.OpenSubKey(file);
object descKey = rkey.GetValue("");
if (descKey != null)
{
string desc = descKey.ToString();
if (!string.IsNullOrEmpty(desc))
{
result.Add(new FileAssoc(file, desc));
}
}
}
}
return result;
}
}
答
我知道这并不回答你的问题,但值得考虑:在很多系统上,这是批次的项目。也许搜索或列表框?
答
我与乔尔同意,那将是一个很大的条目,并试图找到在几百个项目将要结束了一个框列表的东西作为一个非常糟糕的用户体验。除此之外,获得这些信息的唯一方法是像Mitch所说的那样通过注册表,但这不会是简单的代码。
你想完成什么?
编辑: @Mitch小麦,我知道这是给@Mark Brackett,但我无法抗拒挑战。使用LINQ,你的代码可以写为:
public static IList GetFileAssociations()
{
return Registry.ClassesRoot.GetSubKeyNames().Where(key => key.StartsWith(".")).Select(key =>
{
string description = Registry.ClassesRoot.OpenSubKey(key).GetValue("") as string;
if (!String.IsNullOrEmpty(description))
{
return new { key, description };
}
else
{
return null;
}
}).Where(a => a != null).ToList();
}
答
using Microsoft.Win32;
using System.Collections;
internal static class Extensions
{
/// <summary>
/// Gets a dictionary containing known file extensions and description from HKEY_CLASSES_ROOT.
/// </summary>
/// <returns>dictionary containing extensions and description.</returns>
public static Dictionary<string, string> GetAllRegisteredFileExtensions()
{
//get into the HKEY_CLASSES_ROOT
RegistryKey root = Registry.ClassesRoot;
//generic list to hold all the subkey names
Dictionary<string, string> subKeys = new Dictionary<string, string>();
//IEnumerator for enumerating through the subkeys
IEnumerator enums = root.GetSubKeyNames().GetEnumerator();
//make sure we still have values
while (enums.MoveNext())
{
//all registered extensions start with a period (.) so
//we need to check for that
if (enums.Current.ToString().StartsWith("."))
//valid extension so add it and the default description if it exists
subKeys.Add(enums.Current.ToString(), Registry.GetValue(root.Name + "\\" + enums.Current.ToString(), "", "").ToString());
}
return subKeys;
}
}
,这是downvoted为什么呢? – 2009-01-31 00:50:43