My Program cannot write HOSTS file even when run as Admin

7.4k views Asked by At

I have a strange problem. I am writing an application in C# (.Net 4 client profile) which will change entries in the HOSTS file. I added "full access" to my user account for the HOSTS file and I can edit the file without any problems in normal text editors.

The application works find when run in the Visual Studio 2010 Debugger (when "Enable the Visual Studio hosting process" is selected).

When I run the application outside of Visual Studio, even when "run as Admin" (!!!) I can a UnauthorizedAccessException when trying to write the HOSTS file. Why? The detailed information did not gave me any clues:

System.UnauthorizedAccessException was caught
  Message=Der Zugriff auf den Pfad "C:\Windows\System32\drivers\etc\hosts" wurde verweigert.
  Source=mscorlib
  StackTrace:
   bei System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   bei System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
   bei System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
   bei System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   bei System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
   bei System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
   bei System.IO.File.WriteAllLines(String path, String[] contents)
   bei App.HostsFile.Save() in HostsFile.cs:Zeile 125.
   bei App.Actions.SaveHosts.Execute(Context ctxt) in Actions\SaveHosts.cs:Zeile 16.
  InnerException: 
   (there is none)

I have not written a manifest file. I am compiling with the default manifest option. So what is the problem? And what can I do?

Thank you.

2

There are 2 answers

0
Knowleech On

Never mind. I found the culprit. Everything is fine with UAC, but my Kaspersky was blocking my programs :-/

Thank you, Alexander for your help.

4
Alexander V. On

If you have UAC enabled you won't be able to write hosts, even if you're admin, unless you start the program in elevated mode to activate the admin privileges.

Please see here, and here for information on security permissions in code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

    namespace WriteToTheHosts
    {
        class Program
        {
            static void Main(string[] args)
            {
                var systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
                Console.WriteLine(systemPath);
                var path = Path.Combine(systemPath, @"drivers\etc\hosts");
                using (var stream = new StreamWriter(path, true, Encoding.Default))
                {
                    stream.WriteLine("#from .NET");
                }
                Console.ReadKey();

            }
        }
    }

also turn off default manifest in project settings (Manifest: 'Create application without a manifest') and write your own manifest like showed in first link sample:

<?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="WriteToTheHosts" type="win32"/>
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
      <security>
         <requestedPrivileges>
            <requestedExecutionLevel level="requireAdministrator"/>
         </requestedPrivileges>
      </security>
   </trustInfo>
</assembly>