StartupItem.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. using Microsoft.Win32;
  2. using System;
  3. using System.IO;
  4. namespace Optimizer
  5. {
  6. /// <summary>
  7. /// Represents a base Windows startup item
  8. /// </summary>
  9. internal class StartupItem
  10. {
  11. internal string Name { get; set; }
  12. internal string FileLocation { get; set; }
  13. internal StartupItemLocation RegistryLocation { get; set; }
  14. internal StartupItemType StartupType { get; set; }
  15. internal virtual void Remove() { }
  16. internal virtual void LocateFile() { }
  17. internal virtual void LocateKey() { }
  18. public override string ToString()
  19. {
  20. if (RegistryLocation == StartupItemLocation.LMStartupFolder) return RegistryLocation.ToString();
  21. return string.Format("{0}:{1}", RegistryLocation, StartupType);
  22. }
  23. }
  24. internal sealed class FolderStartupItem : StartupItem
  25. {
  26. internal string Shortcut { get; set; }
  27. internal override void Remove()
  28. {
  29. try
  30. {
  31. if (File.Exists(Shortcut))
  32. {
  33. File.Delete(Shortcut);
  34. }
  35. }
  36. catch (Exception ex)
  37. {
  38. Logger.LogError("FolderStartupItem.Remove", ex.Message, ex.StackTrace);
  39. }
  40. }
  41. internal override void LocateFile()
  42. {
  43. try
  44. {
  45. Utilities.FindFile(FileLocation);
  46. }
  47. catch (Exception ex)
  48. {
  49. Logger.LogError("FolderStartupItem.LocateFile", ex.Message, ex.StackTrace);
  50. }
  51. }
  52. }
  53. internal sealed class RegistryStartupItem : StartupItem
  54. {
  55. internal RegistryKey Key { get; set; }
  56. internal override void LocateKey()
  57. {
  58. try
  59. {
  60. Utilities.FindKeyInRegistry(Key.ToString());
  61. }
  62. catch (Exception ex)
  63. {
  64. Logger.LogError("RegistryStartupItem.LocateKey", ex.Message, ex.StackTrace);
  65. }
  66. }
  67. internal override void Remove()
  68. {
  69. try
  70. {
  71. Key.DeleteValue(Name, false);
  72. }
  73. catch (Exception ex)
  74. {
  75. Logger.LogError("RegistryStartupItem.Remove", ex.Message, ex.StackTrace);
  76. }
  77. }
  78. internal override void LocateFile()
  79. {
  80. try
  81. {
  82. Utilities.FindFile(SanitizePath(FileLocation));
  83. }
  84. catch (Exception ex)
  85. {
  86. Logger.LogError("RegistryStartupItem.LocateFile", ex.Message, ex.StackTrace);
  87. }
  88. }
  89. internal string SanitizePath(string s)
  90. {
  91. s = s.Replace("\"", string.Empty);
  92. int i;
  93. while (s.Contains("/"))
  94. {
  95. i = s.LastIndexOf("/");
  96. s = s.Substring(0, i);
  97. }
  98. i = s.IndexOf(".exe");
  99. s = s.Substring(0, i + 4);
  100. return s.Trim();
  101. }
  102. }
  103. }