将文件扩展名与应用程序关联
问题:
作为软件开发人员,您希望允许用户将您的应用程序设置为特定文件类型的默认编辑器。但是,您当前的方法似乎无法正常运行。
响应:
在以下情况下,提供的方法可能会遇到问题:
解决这些问题的替代实现:
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中文网其他相关文章!