Delphi技术实现:按类型获取Windows已注册文件扩展名列表
获取Windows已注册文件扩展名/类型列表的方法
按类型(如Video)筛选的实现方式
1. .NET/C# 自定义实现类似GetExts('Video')的方法
Windows的文件类型关联信息存储在注册表中,你可以通过读取注册表来实现分类获取扩展名的功能。以下是一个C#示例:
using Microsoft.Win32; using System.Collections.Generic; using System.Linq; public static List<string> GetExts(string category) { var exts = new List<string>(); // 系统预定义的文件类型分类路径 string categoryKeyPath = $"HKEY_CLASSES_ROOT\\SystemFileAssociations\\{category.ToLower()}"; try { // 获取该分类下所有关联的扩展名 string[] subKeys = Registry.GetValue(categoryKeyPath, "Extension", null) as string[]; if (subKeys != null) { exts.AddRange(subKeys.Select(ext => ext.StartsWith(".") ? ext : $".{ext}")); } // 额外补充通过ProgID关联的扩展名(部分自定义关联可能在这里) foreach (string ext in Registry.ClassesRoot.GetSubKeyNames().Where(k => k.StartsWith("."))) { using (var extKey = Registry.ClassesRoot.OpenSubKey(ext)) { if (extKey == null) continue; string progId = extKey.GetValue(null) as string; if (string.IsNullOrEmpty(progId)) continue; using (var progIdKey = Registry.ClassesRoot.OpenSubKey($"{progId}\\Shell\\Open\\Command")) { if (progIdKey == null) continue; // 简单判断是否属于目标分类(也可通过查看ProgID的SystemFileAssociations关联) if (progId.ToLower().Contains(category.ToLower()) || Registry.GetValue($"HKEY_CLASSES_ROOT\\{progId}\\SystemFileAssociations", null, null)?.ToString().ToLower() == category.ToLower()) { exts.Add(ext); } } } } // 去重并返回 return exts.Distinct().ToList(); } catch { return exts; } }
调用GetExts("Video")即可获取系统注册的视频类文件扩展名。
2. PowerShell 快速获取
用PowerShell可以直接查询注册表,快速得到指定类型的扩展名:
# 获取视频类扩展名 $videoExts = @() # 读取系统预定义分类 $categoryKey = Get-Item "HKCR:\SystemFileAssociations\video" -ErrorAction SilentlyContinue if ($categoryKey) { $videoExts += $categoryKey.GetValue("Extension") } # 补充自定义关联的扩展名 Get-ChildItem "HKCR:\" | Where-Object {$_.Name -match '^\.'} | ForEach-Object { $progId = $_.GetValue($null) if ($progId) { $progKey = Get-Item "HKCR:\$progId\SystemFileAssociations" -ErrorAction SilentlyContinue if ($progKey -and $progKey.GetValue($null) -eq 'video') { $videoExts += $_.Name.Split('\')[-1] } } } # 去重输出 $videoExts | Select-Object -Unique
3. 直接查看注册表
如果你不需要代码实现,可以手动打开注册表编辑器(regedit),导航到以下路径查看:
HKEY_CLASSES_ROOT\SystemFileAssociations\video:这里存储了系统默认关联的视频扩展名HKEY_CLASSES_ROOT下所有以.开头的项:每个扩展名对应一个项,其中默认值是关联的ProgID,可通过ProgID的SystemFileAssociations子项查看所属分类
内容的提问来源于stack exchange,提问作者ZJ Green
相关产品推荐
相关产品推荐

