在事物的宏偉計劃中......您只需在受保護的區域中編寫結構化文本文件。要做到這一點automatically
與no 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;
}
}
}
不知道我跟着,如果你使用'your.domain.com 127.0.0.1'然後將主機名始終是本地 –
請仔細閱讀==> [我如何問一個很好的問題?( http://stackoverflow.com/help/how-to-ask) ==> [如何創建一個最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve) ==> [我應該避免詢問什麼類型的問題?](http://stackoverflow.com/help/dont-ask) ===> [我可以在這裏詢問什麼主題?](http://stackoverflow.com/幫助/話題) – Hackoo
如果您對C#解決方案開放,我可以幫助您。雖然現在看來,在我有機會向你提供答案之前,你的問題很可能會結束。 –