123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- #region
- using System;
- using System.Diagnostics;
- using System.IO;
- using System.Reflection;
- using System.Text.RegularExpressions;
- #endregion
- namespace CassiniDev
- {
- public static class HostsFile
- {
-
-
-
-
-
-
- public static int AddHostEntry(string ipAddress, string hostname)
- {
- try
- {
- SetHostsEntry(true, ipAddress, hostname);
- return 0;
- }
-
- catch
-
- {
- }
- string executablePath = Assembly.GetExecutingAssembly().Location;
- return StartElevated(executablePath, string.Format("Hostsfile /ah+ /h:{0} /i:{1}", hostname, ipAddress));
- }
-
-
-
-
-
-
- public static int RemoveHostEntry(string ipAddress, string hostname)
- {
- try
- {
- SetHostsEntry(false, ipAddress, hostname);
- return 0;
- }
-
- catch
-
- {
- }
- string executablePath = Assembly.GetExecutingAssembly().Location;
- return StartElevated(executablePath, string.Format("Hostsfile /ah- /h:{0} /i:{1}", hostname, ipAddress));
- }
- private static void SetHostsEntry(bool addHost, string ipAddress, string hostname)
- {
-
- string windir = Environment.GetEnvironmentVariable("SystemRoot") ?? @"c:\windows";
- string hostsFilePath = Path.Combine(windir, @"system32\drivers\etc\hosts");
- string hostsFileContent = File.ReadAllText(hostsFilePath);
- hostsFileContent = Regex.Replace(hostsFileContent,
- string.Format(@"\r\n^\s*[\d\w\.:]+\s{0}\s#\sadded\sby\scassini$",
- hostname), "", RegexOptions.Multiline);
- if (addHost)
- {
- hostsFileContent += string.Format("\r\n{0} {1} # added by cassini", ipAddress, hostname);
- }
- File.WriteAllText(hostsFilePath, hostsFileContent);
- }
- private static int StartElevated(string filename, string args)
- {
- ProcessStartInfo startInfo = new ProcessStartInfo
- {
- UseShellExecute = true,
- WorkingDirectory = Environment.CurrentDirectory,
- FileName = filename,
- Arguments = args,
- Verb = "runas"
- };
- try
- {
- Process p = Process.Start(startInfo);
- if (p != null)
- {
- p.WaitForExit();
- return p.ExitCode;
- }
- return -2;
- }
- catch
- {
- return -2;
- }
- }
- }
- }
|