Retrieving the Default Application for a File Type in Windows
To determine the default application for opening files of a specific type, you can utilize the Windows Registry. In HKEY_CLASSES_ROOT, each file extension has a corresponding key. The default application is stored in the Default value of this key.
Consider the following example for opening HTML files:
This method, however, has limitations. It relies on the registry's implementation, which may differ across Windows versions. A more reliable approach involves the Win32 API function AssocQueryString.
AssocQueryString
AssocQueryString allows you to query the default application for a specific file type.
Syntax:
uint AssocQueryString( AssocF flags, AssocStr str, string pszAssoc, string pszExtra, [Out] StringBuilder pszOut, ref uint pcchOut );
Flags:
Str:
Example:
using System.Runtime.InteropServices; [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)] public static extern uint AssocQueryString( AssocF flags, AssocStr str, string pszAssoc, string pszExtra, [Out] StringBuilder pszOut, ref uint pcchOut ); AssocF flags = AssocF.Open_ByExeName; AssocStr str = AssocStr.Command; StringBuilder sb = new StringBuilder(); uint pcchOut = 0; uint ret = AssocQueryString(flags, str, ".txt", null, sb, ref pcchOut); if (ret == 0) { Console.WriteLine($"Default text editor: {sb.ToString()}"); } else { Console.WriteLine("Error retrieving default text editor."); }
This approach provides a more reliable way to determine the default application for a file type in Windows.
The above is the detailed content of How Can I Programmatically Determine the Default Application for a File Type in Windows?. For more information, please follow other related articles on the PHP Chinese website!