确定在 Windows 上打开文件类型的默认应用程序
使用适当的默认应用程序打开文件是许多应用程序的常见任务。要使用 C# 在 .NET Framework 2.0 中实现此目的,可以利用 System.Diagnostics.Process.Start 方法。但是,此方法需要确切的文件扩展名来确定默认应用程序。
要在所需的默认应用程序中打开没有特定扩展名的文件,您需要检索与该文件类型关联的应用程序。虽然使用注册表来确定这种关联是一种不可靠的方法,但 Win32 API 提供了一种更可靠的方法。
Shlwapi.dll 库中的 AssocQueryString 函数允许您查询特定文件类型的关联。使用此函数,您可以确定文件类型的默认命令、可执行文件或其他相关信息。
示例用法演示了如何利用 AssocQueryString 获取与文件扩展名关联的命令:
using System; using System.Runtime.InteropServices; namespace FileAssociation { class Program { [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); public enum AssocF { None = 0x00000000, Init_NoRemapCLSID = 0x00000001, Init_ByExeName = 0x00000002, Open_ByExeName = 0x00000002, Init_DefaultToStar = 0x00000004, Init_DefaultToFolder = 0x00000008, NoUserSettings = 0x00000010, NoTruncate = 0x00000020, Verify = 0x00000040, RemapRunDll = 0x00000080, NoFixUps = 0x00000100, IgnoreBaseClass = 0x00000200, Init_IgnoreUnknown = 0x00000400, Init_Fixed_ProgId = 0x00000800, Is_Protocol = 0x00001000, Init_For_File = 0x00002000 } public enum AssocStr { Command = 1, Executable, FriendlyDocName, FriendlyAppName, NoOpen, ShellNewValue, DDECommand, DDEIfExec, DDEApplication, DDETopic, InfoTip, QuickTip, TileInfo, ContentType, DefaultIcon, ShellExtension, DropTarget, DelegateExecute, Supported_Uri_Protocols, ProgID, AppID, AppPublisher, AppIconReference, Max } public static string AssocQueryString(AssocStr association, string extension) { const int S_OK = 0x00000000; const int S_FALSE = 0x00000001; 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); // (length - 1) will probably work too as the marshaller adds null termination 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(); } public static void Main(string[] args) { string extension = ".txt"; string command = AssocQueryString(AssocStr.Command, extension); System.Diagnostics.Process.Start(command, "test.txt"); } } }
以上是如何以编程方式确定在 Windows 中打开文件类型的默认应用程序?的详细内容。更多信息请关注PHP中文网其他相关文章!