Example #1
0
        /// <summary>
        /// Parse the hosts file and get all the entries.
        /// </summary>
        /// <returns>Collection of hosts file entries</returns>
        public static GetHostFileEntriesResult GetHostFileEntries(string hostsFilePath = @"C:\Windows\System32\drivers\etc\hosts")
        {
            var result = new GetHostFileEntriesResult();
            if (!File.Exists(hostsFilePath))
            {
                var ex = new FileNotFoundException("Hosts file was not found!", hostsFilePath);
                result.AddException(ex);
                return result;
            }

            var allLines = File.ReadAllLines(hostsFilePath);

            for(int i=0; i < allLines.Count(); i++)
            {
                var line = allLines[i].Trim();

                // Skip blank lines
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                var match = _dnsHostEntryRowPattern.Match(line);
                if (!match.Success)
                {
                    var ex = new FormatException(string.Format("line {0:000} was not formatted as expected. Skipping.", i+1));
                    result.AddException(ex);
                    continue;
                }

                bool enabled = false;
                string ipAddressString = string.Empty;
                string hostNames = string.Empty;
                string comment = string.Empty;
                bool hidden = false;

                enabled = line[0] != '#';
                ipAddressString = match.Groups["ip"].Value.Trim();
                hostNames = match.Groups["hosts"].Value.Trim();
                comment = match.Groups["comment"].Value.Trim();

                // Skip invalid IP address
                IPAddress ipAddress;
                if (!System.Net.IPAddress.TryParse(ipAddressString, out ipAddress))
                {
                    var ex = new FormatException(string.Format("line {0:000} did not have a valid IP address. Skipping.", i+1));
                    result.AddException(ex);
                    continue;
                }

                // Comment
                if (!String.IsNullOrEmpty(comment))
                {
                    hidden = comment[0] == '!';
                    if (hidden)
                    {
                        comment = comment.Substring(1).Trim();
                    }
                }

                DnsHostEntry entry = null;
                var hosts = hostNames.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                foreach (var host in hosts)
                {
                    try
                    {
                        var ub = new UriBuilder(System.Uri.UriSchemeHttp.ToString(), host);
                        entry = new DnsHostEntry(ub.Uri, ipAddress);
                        entry.Enabled = enabled;
                        entry.Comment = comment;
                        entry.IsInHostsFile = true;
                        result.AddEntry(entry);
                    }
                    catch (Exception ex)
                    {
                        var fex = new FormatException(string.Format(@"line {0:000} did not have a valid IP address. Skipping. Full error message:\r\n\{1}", i + 1, ex.GetAllExceptionsString()));
                        result.AddException(fex);
                    }
                }
            }

            return result;
        }
 public void AddEntry(DnsHostEntry entry)
 {
     _entries.Add(entry);
 }
 public void AddException(DnsHostEntry binding, BindingAction action, Exception ex)
 {
     string message = string.Format("Error while {0} binding \"{1}\" to website \"{2}\"", action, binding.DnsSafeDisplayString, binding.Website.Name);
     var newEx = new Exception(message, ex);
     _exceptions.Add(newEx);
 }