0

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.

Knowleech
  • 973
  • 1
  • 8
  • 15

2 Answers2

3

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>
Alexander V.
  • 1,300
  • 11
  • 13
  • Correct me if I am wrong, but right-clicking the Exe and selecting "Run as Administrator" should do the Trick, regardless of the Manifest!? Also: Why CAN I write the file with a Non-Elevated Notepad, but not with my program??? However, thanks for the info and I will look (again) at the things with the manifest. – Knowleech May 26 '12 at 17:08
  • Yes "Run as Administrator" give same privileges as level="requireAdministrator" in manifest. Checked this with my sample code and "Run as Administrator" works ok. Also I checked the notepad and it's can't by default save host file I checked it on my machine (no special user rights changes) – Alexander V. May 26 '12 at 17:31
  • Hm. Okey then. I will check if my Program works on a different computer. Maybe my machine has a problem itself. Thanks for your help. – Knowleech May 27 '12 at 07:14
  • You are welcome! I saw your answer, yeah Kaspersky can do this kind of staff sometimes, I had similar issues with it before in some machines but doesn't keep it in mind at this time. – Alexander V. May 27 '12 at 08:13
1

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

Thank you, Alexander for your help.

Knowleech
  • 973
  • 1
  • 8
  • 15