2009-01-31 36 views

回答

4

所有文件類型都存儲在註冊表中的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; 
    } 
} 
0

我知道這並不回答你的問題,但值得考慮:在很多系統上,這是批次的項目。也許搜索或列表框?

1

我與喬爾同意,那將是一個很大的條目,並試圖找到在幾百個項目將要結束了一個框列表的東西作爲一個非常糟糕的用戶體驗。除此之外,獲得這些信息的唯一方法是像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(); 
} 
+0

,這是downvoted爲什麼呢? – 2009-01-31 00:50:43

1
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; 
    } 
} 
相關問題