HostsHelper.cs 2.8 KB

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