Yohan Aravinda Yohan Aravinda - 3 months ago 24
Vb.net Question

Access isdenied to hosts file

When I run my program in Visual Studio it works perfectly without admin privileges. But when I run program using .exe file error occurred - Access to path

C:/Windows/System32/drivers/etc/host
I tried running it as Administrator, does not work at all!

Here's my code -

Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("C:/Windows/System32/drivers/etc/hosts", True)
file.WriteLine("127.0.0.1 " + www.google.lk)
file.Close()

Answer

Do you have any type of anti-spyware program installed? Some will prevent the hosts file from being modded. This vbscript works for me. Removes read only attribute, performs edit and reapplies read only attribute. Because this has some repeated code, it probably should be modded to have a function to be more "proper".

Set WshShell = WScript.CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

Const ForReading =   1
Const ForWriting =   2
Const ForAppending = 8
Const ReadOnly =     1

strWinDir = WshShell.ExpandEnvironmentStrings("%windir%")
HostsFile = strWinDir & "\System32\drivers\etc\hosts"

Set objFile = objFSO.GetFile(HostsFile)
If objFile.Attributes AND ReadOnly Then
  objFile.Attributes = objFile.Attributes XOR ReadOnly
End If

Set objFile = objFSO.OpenTextFile(HostsFile, ForAppending)
objFile.WriteLine(vbNewLine & "127.0.0.1 www.google.lk")
objFile.Close

Set objFile = objFSO.GetFile(HostsFile)
If Not objFile.Attributes AND ReadOnly Then
  objFile.Attributes = objFile.Attributes XOR ReadOnly
End If

Code to remove same string.

Set WshShell = WScript.CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

Const ForReading =   1
Const ForWriting =   2
Const ForAppending = 8
Const ReadOnly =     1

strWinDir = WshShell.ExpandEnvironmentStrings("%windir%")
HostsFile = strWinDir & "\System32\drivers\etc\hosts"

Set objFile = objFSO.GetFile(HostsFile)
If objFile.Attributes AND ReadOnly Then
  objFile.Attributes = objFile.Attributes XOR ReadOnly
End If

Set objFile = objFSO.OpenTextFile(HostsFile, ForReading)

Do Until objFile.AtEndOfStream
  strLine = objFile.ReadLine
    If InStr(strLine, "127.0.0.1 www.google.lk") = 0 Then
      strContents = strContents & strLine & vbCrLf
    End If
Loop
objFile.Close

Set objFile = objFSO.OpenTextFile(HostsFile, ForWriting)
objFile.Write strContents
objFile.Close

Set objFile = objFSO.GetFile(HostsFile)
If Not objFile.Attributes AND ReadOnly Then
  objFile.Attributes = objFile.Attributes XOR ReadOnly
End If