2017-06-27 88 views
0

我開發了多個應用程序並將它們託管在工作筆記本電腦上用於本地調試。爲了訪問這些網站,我輸入了一個主機文件重定向到筆記本電腦IP地址的URL。Windows自動更新本地計算機IP地址的主機文件

我的問題是如何自動更新我的主機文件以將這些URL映射到機器的當前IP地址。

這會非常有幫助,因爲我將機器放在我的桌子上並接收一個IP地址,然後走到會議連接到WiFi並接收另一個IP地址。如果我再也不用擔心這件事,那將是非常棒的。

+0

不知道我跟着,如果你使用'your.domain.com 127.0.0.1'然後將主機名始終是本地 –

+2

請仔細閱讀==> [我如何問一個很好的問題?( http://stackoverflow.com/help/how-to-ask) ==> [如何創建一個最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve) ==> [我應該避免詢問什麼類型的問題?](http://stackoverflow.com/help/dont-ask) ===> [我可以在這裏詢問什麼主題?](http://stackoverflow.com/幫助/話題) – Hackoo

+0

如果您對C#解決方案開放,我可以幫助您。雖然現在看來,在我有機會向你提供答案之前,你的問題很可能會結束。 –

回答

0

在事物的宏偉計劃中......您只需在受保護的區域中編寫結構化文本文件。要做到這一點automaticallyno user interaction您首先需要用戶獲得您的應用程序許可才能這樣做。一旦你獲得了訪問權限,它就像往常一樣工作。

下面是我爲改變主機文件而編寫的應用程序的一個稍微修改後的副本/粘貼。原來,它並不完全符合你想要做的事情,但是,所有事情都是爲你量身定做的。按原樣,這是一個命令行工具。

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Security.Principal; 

namespace ModifyHostFile 
{ 
    class Program 
    { 
     const string HostFileLocation = @"C:\Windows\System32\drivers\etc\hosts"; 
     const string HostFileTmpLocation = @"C:\Windows\System32\drivers\etc\hosts_tmp"; 

     static void Main(string[] args) 
     { 
      WelcomeUser(); 

      if (args.Length == 0) 
      { 
       Console.WriteLine("Must supply action switch [A]dd, or [R]emove entries"); 
       args = new string[1]; 
       args.SetValue(Console.ReadLine(), 0); 
      } 

      switch (args[0].ToUpper()) 
      { 
       case "A": 
        Console.WriteLine("Ok, this will ADD entries in your HOST file."); 
        AddEntriesToHostFile(); 
        break; 
       case "R": 
        Console.WriteLine("Ok, this will REMOVE entries from your HOST file."); 
        RemoveOurEntriesFromHostFile(); 
        break; 
       case "EXIT": 
        Environment.Exit(0); 
        break; 
       default: 
        Console.WriteLine("Action switch not recognized."); 
        Console.WriteLine("Press ENTER to quit"); 
        Console.ReadLine(); 
        return; 
      } 

      Console.WriteLine("Done."); 
      Console.WriteLine("Press ENTER to quit."); 
      Console.ReadLine(); 
      return; 
     } 

     private static void WelcomeUser() 
     { 
      int padCount = 119; 
      char padChar = '#'; 
      List<string> messageLines = new List<string>(); 
      messageLines.Add("#"); 
      messageLines.Add("Welcome to \"Modify Host File\""); 
      messageLines.Add("This tool can execute 2 actions."); 
      messageLines.Add("It can add specific entries to your Host file."); 
      messageLines.Add("It can remove specific entries from your host file."); 
      messageLines.Add("Entries are removed so you can get your original file back."); 
      messageLines.Add("#"); 

      messageLines = messageLines.Select(p => p.PadForConsole(padChar, padCount)).ToList(); 

      foreach (string item in messageLines) 
      { 
       ConsoleColor originalColor = Console.ForegroundColor; 
       Console.ForegroundColor = ConsoleColor.Green; 
       Console.WriteLine(item); 
       Console.ForegroundColor = originalColor; 
      } 
      Console.WriteLine(); 
      Console.WriteLine(); 
     } 

     public static void RemoveOurEntriesFromHostFile() 
     { 
      HostEntriesToadd entries = new ModifyHostFile.HostEntriesToadd(); 
      try 
      { 
       using (StreamReader sr = new StreamReader(HostFileLocation)) 
       { 
        using (StreamWriter sw = new StreamWriter(HostFileTmpLocation, false)) 
        { 
         string currentLine = string.Empty; 
         while ((currentLine = sr.ReadLine()) != null) 
         { 
          if (entries.Contains(currentLine)) 
          { 
           //don't write the line 
           Console.WriteLine("Removed " + currentLine + " from host file"); 
          } 
          else 
          { 
           //write the line 
           sw.WriteLine(currentLine); 
          } 
         } 
        } 
       } 
       ReplaceTheFiles(HostFileTmpLocation, HostFileLocation); 
      } 
      catch (System.UnauthorizedAccessException) 
      { 
       WarnForElevatedPermissions(); 
      } 

     } 

     public static void AddEntriesToHostFile() 
     { 
      HostEntriesToadd entries = new ModifyHostFile.HostEntriesToadd(); 
      try 
      { 
       using (StreamWriter sw = new StreamWriter(HostFileTmpLocation, false)) 
       { 
        sw.Write(File.ReadAllText(HostFileLocation)); 
        foreach (string item in entries) 
        { 
         sw.WriteLine(item); 
         Console.WriteLine("Added " + item + " from host file"); 
        } 
       } 
       ReplaceTheFiles(HostFileTmpLocation, HostFileLocation); 
      } 
      catch (System.UnauthorizedAccessException) 
      { 
       WarnForElevatedPermissions(); 
      } 

     } 

     private static void WarnForElevatedPermissions() 
     { 
      ConsoleColor originalColor = Console.ForegroundColor; 
      Console.ForegroundColor = ConsoleColor.Red; 
      Console.WriteLine("Access Violation Exception"); 
      if (!IsAdministrator()) 
      { 
       Console.ForegroundColor = ConsoleColor.Red; 
       Console.WriteLine("IsAdministrator: False"); 
       Console.ForegroundColor = originalColor; 
      } 
      else 
      { 
       Console.ForegroundColor = ConsoleColor.Red; 
       Console.WriteLine("IsAdministrator: True"); 
       Console.ForegroundColor = originalColor; 
      } 
      Console.ForegroundColor = originalColor; 
      Console.WriteLine("This tool will re-write your System's host file."); 
      Console.WriteLine("Because your System's host file resides in a protected area on your computer"); 
      Console.WriteLine("this tool MUST run with elevated permissions, aka run as administrator."); 

      Console.WriteLine(""); 
     } 

     public static bool ReplaceTheFiles(string FileToReplaceWith, string FileToReplace) 
     { 
      try 
      { 
       File.Copy(FileToReplaceWith, FileToReplace, true);//overwrite the old file 
       File.Delete(FileToReplaceWith);//delete the tmp file 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e); 
       return false; 
      } 
      return true; 
     } 

     public static bool IsAdministrator() 
     { 
      return (new WindowsPrincipal(WindowsIdentity.GetCurrent())) 
        .IsInRole(WindowsBuiltInRole.Administrator); 
     } 

    } 



    public class HostEntriesToadd : List<string> 
    { 
     public HostEntriesToadd() 
     { 
      this.Add("127.0.0.1 www.somesite.com"); 
      this.Add("127.0.0.1 someothersite.com"); 
      this.Add("127.0.0.1 blahblahblah.com"); 
      this.Add("127.0.0.1 damnthatdamn.com"); 
      this.Add("127.0.0.1 whateveryouwant.com"); 
     } 
    } 

    public static class StringHelpers 
    { 
     public static string PadForConsole(this string Text, char PadWith, int TotalLineLength) 
     { 
      List<string> texts = new List<string>(); 
      texts.Add(Text); 
      if (texts[0].Length >= TotalLineLength - 2) 
      { 
       texts.Add(string.Empty); 
       for (int i = 0; i < texts[0].Length; i++) 
       { 
        if (texts.Last().Length < TotalLineLength - 2) 
        { 
         texts[texts.Count - 1] = texts[texts.Count - 1] + texts[0][i]; 
        } 
        else 
        { 
         texts.Add(texts[0][i].ToString()); 
        } 
       } 
       texts.RemoveAt(0); 
      } 

      for (int i = 0; i < texts.Count; i++) 
      { 
       string currentLine = texts[i].ToString(); 
       int leftPadCount = ((TotalLineLength - currentLine.Length)/2); 
       string leftPadString = new string(PadWith, leftPadCount); 
       //int rightPadCount = (TotalLineLength - currentLine.Length)/2; 
       int rightPadCount = (TotalLineLength - currentLine.Length - leftPadCount); 
       string rightPadString = new string(PadWith, rightPadCount); 
       texts[i] = string.Format("{0}{1}{2}", leftPadString, texts[i], rightPadString); 
      } 
      string retVal = string.Empty; 
      retVal = string.Join(System.Environment.NewLine, texts); 
      return retVal; 
     } 
    } 
} 
相關問題