將檔案副檔名與應用程式關聯
問題:
問題:作為軟體開發人員,您希望允許使用者將您的應用程式設定為特定檔案類型的預設編輯器。但是,您目前的方法似乎無法正常運作。
回應:public class FileAssociation { public string Extension { get; set; } public string ProgId { get; set; } public string FileTypeDescription { get; set; } public string ExecutableFilePath { get; set; } } public static class FileAssociations { static FileAssociations() { SetDllDirectory(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)); } [DllImport("shell32.dll", CharSet = CharSet.Unicode)] extern static int SHChangeNotify(int wEventId, int uFlags, IntPtr dwItem1, IntPtr dwItem2); const int SHCNE_ASSOCCHANGED = 0x8000000; const int SHCNF_FLUSH = 0x1000; public static void EnsureAssociationsSet(params FileAssociation[] associations) { var changesMade = false; foreach (var association in associations) { changesMade |= SetAssociation( association.Extension, association.ProgId, association.FileTypeDescription, association.ExecutableFilePath); } if (changesMade) SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH, IntPtr.Zero, IntPtr.Zero); } public static bool SetAssociation(string extension, string progId, string fileTypeDescription, string applicationFilePath) { var changesMade = false; using (RegistryKey extensionKey = RegistryKey.CurrentUser.CreateSubKey($@"Software\Classes\{extension}")) { changesMade |= SetKeyDefaultValue(extensionKey, null, progId); } using (RegistryKey progIdKey = RegistryKey.CurrentUser.CreateSubKey($@"Software\Classes\{progId}")) { changesMade |= SetKeyDefaultValue(progIdKey, null, fileTypeDescription); changesMade |= SetKeyDefaultValue(progIdKey.CreateSubKey(@"shell\open\command"), null, $"\"{applicationFilePath}\" \"%1\""); } return changesMade; } static bool SetKeyDefaultValue(RegistryKey key, string name, object value) { var originalValue = key.GetValue(name); if (value == null) { if (originalValue == null) return false; key.DeleteValue(name); return true; } if (value is string && originalValue is string && (string)value == (string)originalValue) return false; key.SetValue(name, value); return true; } }
以上是如何在 C# 中可靠地將檔案副檔名與應用程式關聯起來?的詳細內容。更多資訊請關注PHP中文網其他相關文章!