potisanのプログラミングメモ

趣味のプログラマーがプログラミング関係で気になったことや調べたことをいつでも忘れられるようにメモするブログです。はてなブログ無料版なので記事の上の方はたぶん広告です。記事中にも広告挿入されるみたいです。

C# Windows 10のレジストリを直接参照して登録アプリケーションのSupportedTypesを取得するコード

動作確認環境:Windows 10、C#、.NET Core 3.1

レジストリを直接参照して登録アプリケーションのSupportedTypesを取得するコードです。shlwapi.dllのIQueryAssociationsは列挙に非対応なので、一覧を取得する場合はこのように直接取得するしかないかもしれません。

using System;
using System.Collections.Generic;
using Microsoft.Win32;

class Program
{
    static void Main()
    {
        var appNameAndSupportedTypes = GetRegistedApplicationNameAndSupportedTypes(true);
        foreach ((string appName, string[] supportedTypes) in appNameAndSupportedTypes)
        {
            Console.WriteLine($"{appName}: {string.Join<string>(';', supportedTypes)}");
        }
        // mspaint.exe: .bmp;.dib;.emf;.gif;.ico;.jfif;.jpe;.jpeg;.jpg;.png;.rle;.tif;.tiff;.wmf
        // firefox.exe: .htm;.html;.shtml;.xht;.xhtml;.svg;.webp
        // ...
    }

    static Dictionary<string, string[]> GetRegistedApplicationNameAndSupportedTypes(
        bool includesNoSupportedTypes)
    {
        using var hkcr = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry64);
        using var appsKey = hkcr.OpenSubKey("Applications");

        var appNameAndSupportedTypes = new Dictionary<string, string[]>();
        foreach (var appName in appsKey.GetSubKeyNames())
        {
            using var suportedTypesKey = appsKey.OpenSubKey(appName + "\\SupportedTypes");
            if (suportedTypesKey != null )
            {
                appNameAndSupportedTypes.Add(appName, suportedTypesKey.GetValueNames());
            }
            else if (includesNoSupportedTypes)
            {
                appNameAndSupportedTypes.Add(appName, new string[0]);
            }
        }
        return appNameAndSupportedTypes;
    }
}

Applicationsレジストリキーに関する公式ドキュメントは以下です。