確定在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中文網其他相關文章!