I'm writing a little WPF utility to manage entries in the hosts file for dev purposes. As you might know the hosts file is protected by the newer OSs (Win 7/2008/Vista).
I've added a manifest to my application to set the requestedExecutionLevel to "requireAdministrator", as detailed here (using "the easy way") and in the related question here.
Unfortunately this has not worked for me. There is no elevation prompt when I start the app, and calling File.AppendText for the hosts file still causes a System.UnauthorizedAccessException to be thrown: "Access to the path 'C:\Windows\System32\drivers\etc\hosts' is denied."
HostsChanger.exe.manifest:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="HostsChanger" type="win32"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
Any ideas?
Paraphrased from my earlier comment, turned into an answer:
The answer ho1 gave contains an app.manifest that is exactly the same as the app I'm working on at work, and elevation is working for it. The difference here is that the filename is "app.manifest", and the project option "Manifest" (on the Application tab) is pointing to it.
I'm not sure if it'll make any difference but your manifest snippet is slightly different from my understanding of how it should be (though that might be different versions):
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<assemblyIdentity version="1.0.0.0" name="HostsChanger" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
</asmv1:assembly>
Otherwise, a work around might be to have a separate "Loader" app that the user starts with and that only starts your real WPF tool using the Verb
runas
as detailed in this blog post (so Process.StartInfo.Verb = "runas";
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With