ExtensionAttach.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using Microsoft.Win32;
  2. using System;
  3. using System.IO;
  4. using System.Security;
  5. namespace Masuit.Tools.Files
  6. {
  7. /// <summary>
  8. /// 文件关联
  9. /// </summary>
  10. public static class ExtensionAttach
  11. {
  12. /// <summary>
  13. /// 关联文件
  14. /// </summary>
  15. /// <param name="filePathString">应用程序路径</param>
  16. /// <param name="pFileTypeName">文件类型</param>
  17. /// <exception cref="SecurityException">The user does not have the permissions required to access the registry key in the specified mode. </exception>
  18. /// <exception cref="UnauthorizedAccessException">The user does not have the necessary registry rights.</exception>
  19. /// <exception cref="IOException">The nesting level exceeds 510.-or-A system error occurred, such as deletion of the key, or an attempt to create a key in the <see cref="F:Microsoft.Win32.Registry.LocalMachine" /> root.</exception>
  20. public static void SaveReg(string filePathString, string pFileTypeName)
  21. {
  22. RegistryKey regKey = Registry.ClassesRoot.OpenSubKey("", true); //打开注册表
  23. RegistryKey vrPkey = regKey?.OpenSubKey(pFileTypeName, true);
  24. if (vrPkey != null)
  25. {
  26. regKey.DeleteSubKey(pFileTypeName, true);
  27. }
  28. regKey?.CreateSubKey(pFileTypeName);
  29. vrPkey = regKey?.OpenSubKey(pFileTypeName, true);
  30. vrPkey?.SetValue("", "Exec");
  31. vrPkey = regKey?.OpenSubKey("Exec", true);
  32. if (vrPkey != null) regKey.DeleteSubKeyTree("Exec"); //如果等于空就删除注册表DSKJIVR
  33. regKey?.CreateSubKey("Exec");
  34. vrPkey = regKey?.OpenSubKey("Exec", true);
  35. vrPkey?.CreateSubKey("shell");
  36. vrPkey = vrPkey?.OpenSubKey("shell", true); //写入必须路径
  37. vrPkey?.CreateSubKey("open");
  38. vrPkey = vrPkey?.OpenSubKey("open", true);
  39. vrPkey?.CreateSubKey("command");
  40. vrPkey = vrPkey?.OpenSubKey("command", true);
  41. string pathString = "\"" + filePathString + "\" \"%1\"";
  42. vrPkey?.SetValue("", pathString); //写入数据
  43. }
  44. /// <summary>
  45. /// 取消文件关联
  46. /// </summary>
  47. /// <param name="pFileTypeName">文件类型</param>
  48. /// <exception cref="SecurityException">The user does not have the permissions required to access the registry key in the specified mode. </exception>
  49. /// <exception cref="UnauthorizedAccessException">The user does not have the necessary registry rights.</exception>
  50. /// <exception cref="IOException">An I/O error has occurred.</exception>
  51. public static void DelReg(string pFileTypeName)
  52. {
  53. RegistryKey regkey = Registry.ClassesRoot.OpenSubKey("", true);
  54. RegistryKey vrPkey = regkey?.OpenSubKey(pFileTypeName);
  55. if (vrPkey != null)
  56. {
  57. regkey.DeleteSubKey(pFileTypeName, true);
  58. }
  59. if (vrPkey != null)
  60. {
  61. regkey.DeleteSubKeyTree("Exec");
  62. }
  63. }
  64. }
  65. }