Finding the Default Application for File Types in Windows
Developers often need to find the default application associated with a specific file type. This is important for tasks such as invoking the default editor for a particular file extension.
To achieve this, one might consider using System.Diagnostics.Process.Start to open a file in its default application. However, this approach is limited and doesn't allow for the opening of files with non-standard extensions.
The reliable solution involves using the Win32 API function AssocQueryString. This function enables querying the operating system for the default application associated with a file type.
Here's how you can leverage AssocQueryString in C#:
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 ); [Flags] public enum AssocF { // ... } public enum AssocStr { // ... } public static string AssocQueryString(AssocStr association, string extension) { const int S_OK = 0; const int S_FALSE = 1; uint length = 0; uint ret = AssocQueryString(AssocF.None, association, extension, null, null, ref length); if (ret != S_FALSE) { throw new InvalidOperationException("Could not determine associated string"); } var sb = new StringBuilder((int)length); ret = AssocQueryString(AssocF.None, association, extension, null, sb, ref length); if (ret != S_OK) { throw new InvalidOperationException("Could not determine associated string"); } return sb.ToString(); }
By calling AssocQueryString and specifying the desired association, you can retrieve the full path to the default application. This allows you to directly interact with the default editor or processor for a particular file type, even if the file doesn't have a standard extension.
The above is the detailed content of How Can I Programmatically Find the Default Application for a Specific File Type in Windows?. For more information, please follow other related articles on the PHP Chinese website!