JRD*_*RDH 8 c c# c++ windows hosts-file
C++/C/C#程序中的程序如何更改C:\Windows\System32\drivers\etc\hostsWindows中的文件内容?我知道这听起来像网络钓鱼,老实说不是.
Lot*_*tfi 13
主机文件的格式非常简单,每行可能包含"ip host"记录
您只需要附加常规文件:
using (StreamWriter w = File.AppendText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers/etc/hosts")))
{
w.WriteLine("123.123.123.123 FQDN");
}
Run Code Online (Sandbox Code Playgroud)
请注意,默认情况下,您需要提升权限才能写入hosts文件...
为了还原,最好备份文件并在完成后恢复它.
Dav*_*son 13
首先,您应该请求用户的管理许可.您可以通过应用程序中的Program类完成此操作.以下代码将请求用户进行管理访问,然后用户可以选择允许或拒绝它.如果他们否认它,此示例不会运行该应用程序.
应用程序在管理模式下运行后,其纯文本格式简单.你甚至不需要文件中包含的所有Microsoft注释,简单的字符串解析就可以了.MSFT在HOSTS文件中的注释是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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
该文件通常位于C:\Windows\System32\drivers\etc\hosts.C:\Windows您应该使用Environment.GetEnvironmentVariable("SystemRoot")安全地确定系统根目录,而不是对部件进行硬编码.
否则,您可以像任何其他文件一样写入它,假设您具有适当的权限.
主机文件只是纯文本。格式是每行包含 IP 和 IP 应解析为的主机名,以空格分隔。#表示评论。
例子:
# This is a comment-
127.0.0.1 mysuperhost.com
Run Code Online (Sandbox Code Playgroud)
该文件位于此处:C:\Windows\system32\drivers\etc\hosts. 您将(有充分的理由)需要管理员权限才能写入它。
| 归档时间: |
|
| 查看次数: |
20935 次 |
| 最近记录: |