Associating File Extensions with Applications
Problem:
As a software developer, you want to allow users to set your application as the default editor for a specific file type. However, your current method doesn't seem to function correctly.
Response:
The provided method may encounter issues if:
An alternative implementation that addresses these concerns:
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; } }
The above is the detailed content of How to Reliably Associate File Extensions with Applications in C#?. For more information, please follow other related articles on the PHP Chinese website!