FileAssociation.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Microsoft.Win32;
  8. namespace MECF.Framework.Common.Utilities
  9. {
  10. public class FileAssociation
  11. {
  12. [DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  13. public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);
  14. public static void SetAssociation(string Extension, string KeyName, string OpenWith, string FileDescription)
  15. {
  16. // The stuff that was above here is basically the same
  17. RegistryKey BaseKey;
  18. RegistryKey OpenMethod;
  19. RegistryKey Shell;
  20. RegistryKey CurrentUser;
  21. BaseKey = Registry.ClassesRoot.CreateSubKey(Extension);
  22. BaseKey.SetValue("", KeyName);
  23. OpenMethod = Registry.ClassesRoot.CreateSubKey(KeyName);
  24. OpenMethod.SetValue("", FileDescription);
  25. OpenMethod.CreateSubKey("DefaultIcon").SetValue("", "\"" + OpenWith + "\",0");
  26. Shell = OpenMethod.CreateSubKey("Shell");
  27. Shell.CreateSubKey("edit").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\"");
  28. Shell.CreateSubKey("open").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\"");
  29. BaseKey.Close();
  30. OpenMethod.Close();
  31. Shell.Close();
  32. // Delete the key instead of trying to change it
  33. CurrentUser = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\" + Extension, true);
  34. CurrentUser.DeleteSubKey("UserChoice", false);
  35. CurrentUser.Close();
  36. // Tell explorer the file association has been changed
  37. SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);
  38. }
  39. }
  40. }