私は数多くの方法で試してきましたが、「管理者としてアプリケーションを開きますか? 'ホストファイルに新しいエントリを追加する警告を回避/処理するコードを提案する人もいます。それとも他の任意のウイルスhostsファイルをハイジャックし、悪質なサイトへのすべてのブラウザ要求をリダイレクトすることができ - 事前に 感謝..管理者権限でC#を使用して手動で管理することなくホストファイルを変更する方法
public bool ModifyHostsFile(string sEntryIPAddr, string sEntryURL)
{
try
{
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;
//Process.Start(startInfo);
//bool bStatus = GrantAccess(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc\hosts"));
using (StreamWriter w = File.AppendText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc\hosts")))
{
w.WriteLine(sEntryIPAddr + " " + sEntryURL);
}
Application.Exit();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
private bool GrantAccess(string fullPath)
{
DirectoryInfo dInfo = new DirectoryInfo(fullPath);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);
return true;
}
UACを無効にする方法はありますが、誰もがそれを望むとは思わない... – Prix