Windowsで登録されているすべてのファイルタイプでComboBoxを埋めるのに最も効率的なのは何ですか?
拡張子だけでなく、完全なファイルの種類が必要です。私はVB 9(VS2008)を使用しています。
すべてのファイル タイプは、HKEY_CLASS_ROOT の下のレジストリに格納されます。これは、フレームワークのRegistry クラスを使用して取得できます。
タスクを実行するための 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;
}
}
Joelに同意します。これは多くのエントリになり、何百ものアイテムのコンボボックスリストで何かを見つけようとすると、ユーザーエクスペリエンスが非常に悪くなります。それ以外は、ミッチが言うように、この情報を取得する唯一の方法はレジストリを調べることですが、それは単純なコードではありません。
何を達成しようとしていますか?
編集: @Mitch Wheat、これが@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;
}
}
これであなたの質問に答えられないことはわかっていますが、検討する価値はあります。多くのシステムでは、それはたくさんのアイテムです。おそらく代わりに検索またはリストボックスでしょうか?