C++/ C/ C#程序如何改变windows中的C:\Windows\System32\drivers\etc\hosts文件内容?我知道这听起来像是网络钓鱼,老实说不是。
发布于 2011-06-30 05:12:43
Hosts文件有一个非常简单的格式,其中每一行都可以包含"ip host“记录
你所需要的就是常规的文件附加:
using (StreamWriter w = File.AppendText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers/etc/hosts")))
{
w.WriteLine("123.123.123.123 FQDN");
}请注意,默认情况下,您需要提升权限才能写入主机文件...
为了恢复,最好对文件进行备份,并在备份完成后将其恢复。
发布于 2011-06-30 05:29:23
首先,您应该向用户请求的管理权限。您可以通过应用程序中的Program类完成此操作。下面的代码将请求用户进行管理访问,然后用户可以选择允许或拒绝。如果他们拒绝,此示例将不会运行应用程序。
一旦您的应用程序在管理模式下运行,它就会显示具有简单格式的纯文本。您甚至不需要文件中包含的所有Microsoft注释,简单的字符串解析就足够了。就HOSTS文件本身而言,MSFT在HOSTS文件中的注释是您真正需要的所有文档。
namespace Setup {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Setup.Forms;
using System.Security.Principal;
using System.Diagnostics;
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool administrativeMode = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (!administrativeMode) {
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Verb = "runas";
startInfo.FileName = Application.ExecutablePath;
try {
Process.Start(startInfo);
}
catch {
return;
}
return;
}
Application.Run(new ShellForm());
}
}
}发布于 2011-06-30 05:10:34
该文件通常位于C:\Windows\System32\drivers\etc\hosts。不过,您应该使用Environment.GetEnvironmentVariable("SystemRoot")来安全地确定系统根目录,而不是对C:\Windows部件进行硬编码。
否则,您可以像任何其他文件一样写入该文件,前提是您具有适当的权限。
https://stackoverflow.com/questions/6527229
复制相似问题