Im großen Schema der Dinge ... Alles, was Sie tun müssen, ist eine strukturierte Textdatei in einem geschützten Bereich zu schreiben. Um dies zu tun automatically
mit no user interaction
müssen Sie zuerst den Benutzer, um Ihre Anwendung Erlaubnis groß zu tun, dies zu tun. Sobald Sie Zugang erhalten haben, ist es wie gewohnt.
Unten ist eine leicht modifizierte Kopie/Paste einer Anwendung, die ich schrieb, um eine Host-Datei zu ändern. So wie es ist, tut es nicht genau das, was DU tun willst, aber alles ist da, damit du es entsprechend anpassen kannst. Wie es ist, ist dies ein Befehlszeilenwerkzeug.
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;
}
}
}
nicht sicher, ob ich folgen, wenn Sie 'verwenden your.domain.com 127.0.0.1' dann der Host-Name immer lokal sein –
Bitte sorgfältig lesen ==> [Wie stelle ich eine gute Frage?] (http://stackoverflow.com/help/how-to-ask) ==> [Erstellen eines minimalen, vollständigen und überprüfbaren Beispiels] (http://stackoverflow.com/help/mcve) ==> [Welche Arten von Fragen sollte ich vermeiden zu fragen?] (Http://stackoverflow.com/help/dont-ask) ===> [Welche Themen kann ich hier fragen?] (Http://stackoverflow.com/ Hilfe/on-topic) – Hackoo
Wenn Sie offen für eine C# Lösung sind, kann ich Ihnen wahrscheinlich helfen. Aber so wie es jetzt aussieht, wird Ihre Frage wahrscheinlich geschlossen, bevor ich die Möglichkeit habe, Ihnen eine Antwort zu geben. –