StartupItem.cs 2.8 KB

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