HostsHelper.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.IO;
  5. using System.Text.RegularExpressions;
  6. namespace Optimizer
  7. {
  8. internal static class HostsHelper
  9. {
  10. internal static string NewLine = Environment.NewLine;
  11. internal static readonly string HostsFile = CleanHelper.System32Folder + "\\drivers\\etc\\hosts";
  12. internal static void RestoreDefaultHosts()
  13. {
  14. try
  15. {
  16. if (File.Exists(HostsFile))
  17. {
  18. File.Delete(HostsFile);
  19. }
  20. File.WriteAllBytes(HostsFile, Properties.Resources.hosts);
  21. }
  22. catch { }
  23. }
  24. internal static string[] ReadHosts()
  25. {
  26. return File.ReadAllLines(HostsFile);
  27. }
  28. internal static void LocateHosts()
  29. {
  30. Utilities.FindFile(HostsFile);
  31. }
  32. internal static void SaveHosts(string[] lines)
  33. {
  34. for (int i = 0; i < lines.Length; i++)
  35. {
  36. if (!lines[i].StartsWith("#") && (!string.IsNullOrEmpty(lines[i])))
  37. {
  38. lines[i] = SanitizeEntry(lines[i]);
  39. }
  40. }
  41. File.WriteAllText(HostsFile, string.Empty);
  42. File.WriteAllLines(HostsFile, lines);
  43. }
  44. internal static List<string> GetHostsEntries()
  45. {
  46. List<string> entries = new List<string>();
  47. string[] lines = File.ReadAllLines(HostsFile);
  48. foreach (string line in lines)
  49. {
  50. if (!line.StartsWith("#") && (!string.IsNullOrEmpty(line)))
  51. {
  52. entries.Add(line.Replace(" ", " : "));
  53. }
  54. }
  55. return entries;
  56. }
  57. internal static void AddEntry(string entry)
  58. {
  59. try
  60. {
  61. File.AppendAllText(HostsFile, NewLine + entry);
  62. }
  63. catch { }
  64. }
  65. internal static void RemoveEntry(string entry)
  66. {
  67. try
  68. {
  69. File.WriteAllLines(HostsFile, File.ReadLines(HostsFile).Where(x => x != entry).ToList());
  70. }
  71. catch { }
  72. }
  73. internal static void RemoveAllEntries(List<string> collection)
  74. {
  75. try
  76. {
  77. foreach (string text in collection)
  78. {
  79. File.WriteAllLines(HostsFile, File.ReadLines(HostsFile).Where(l => l != text).ToList());
  80. }
  81. }
  82. catch { }
  83. }
  84. internal static string SanitizeEntry(string entry)
  85. {
  86. // remove multiple white spaces and keep only one
  87. return Regex.Replace(entry, @"\s{2,}", " ");
  88. }
  89. internal static bool GetReadOnly()
  90. {
  91. return new FileInfo(HostsFile).IsReadOnly;
  92. }
  93. internal static void ReadOnly(bool enable)
  94. {
  95. FileInfo fi = new FileInfo(HostsFile);
  96. fi.IsReadOnly = enable;
  97. }
  98. }
  99. }