Hey peps

I've just used this code to block a website

Imports System.IO
Public Class Form1
    Dim path As String
    Dim sw As StreamWriter
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        path = "C:\Windows\System32\drivers\etc\hosts"
        sw = New StreamWriter(path, True)
        Dim Block As String = "\n www.youporn.com"
        MsgBox("Site has been registered to system to be blocked", MsgBoxStyle.Information, Application.ProductName)
    End Sub
End Class

how can I read the hosts file and remove the address that I've just registered because I can not delete the Host file like this.


I want to read it inside and only remove the name I've just entered without interfearing with other names writen inside this file.

Recommended Answers

All 7 Replies

You will have to re-write the file.


Dim SR as New StreamReader(path)
Dim SW as New StreamWriter(path & "tmp")

Do While SR.Peek <> -1
    Dim sCur As String = SR.ReadLine
    If sCur <> Block Then
    End If


'Next Copy Over the original hosts file 
File.Copy(path & "tmp", path,True)

If you use a list of strings and the readalllines and the writealllines methods, you can read manipulate and overwrite the file without any extra coding. Here's one way of doing it:

Imports System.IO
Imports System
Imports System.Linq
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Public Class Form3
    Friend WithEvents ListView1 As System.Windows.Forms.ListView
    Friend WithEvents ColumnHeader1 As System.Windows.Forms.ColumnHeader
    Friend WithEvents ColumnHeader2 As System.Windows.Forms.ColumnHeader
    Dim FilePath As String = "C:\Windows\System32\drivers\etc\hosts"
    Dim IPList As List(Of String)

    Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.ListView1 = New System.Windows.Forms.ListView()
        Me.ColumnHeader1 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
        Me.ColumnHeader2 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
        Me.ListView1.AllowColumnReorder = True
        Me.ListView1.BackgroundImageTiled = True
        Me.ListView1.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.ColumnHeader1, Me.ColumnHeader2})
        Me.ListView1.FullRowSelect = True
        Me.ListView1.GridLines = True
        Me.ListView1.Location = New System.Drawing.Point(19, 12)
        Me.ListView1.MultiSelect = False
        Me.ListView1.Name = "ListView1"
        Me.ListView1.Size = New System.Drawing.Size(419, 229)
        Me.ListView1.TabIndex = 3
        Me.ListView1.UseCompatibleStateImageBehavior = False
        Me.ListView1.View = System.Windows.Forms.View.Details
        Me.ColumnHeader1.Text = "Source Address"
        Me.ColumnHeader1.Width = 280
        Me.ColumnHeader2.Text = "Dest. Ip"
        Me.ColumnHeader2.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
        Me.ColumnHeader2.Width = 114
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(480, 241)
        Me.Name = "Form3"
        Me.Text = "Form3"
    End Sub
    Public Sub LoadListview()
        IPList = New List(Of String)(File.ReadAllLines(FilePath, Encoding.Default).ToList)
        For Each Line As String In IPList
            If Not ((Line.StartsWith("#")) Or (Line = "")) Then
                Dim Ln() As String = Line.Split(" ")
                For i = 0 To Ln.Count - 1
                    If Not String.IsNullOrEmpty(Ln(i)) Then
                        If Not IsNumeric(Ln(i).Substring(0, 1)) Then
                        End If
                    End If
            End If
    End Sub

    Private Sub ListView1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.Click
        Dim Result As DialogResult = MessageBox.Show(ListView1.SelectedItems(0).Text + " " + ListView1.SelectedItems(0).SubItems(1).Text, "Confirm Delete?", MessageBoxButtons.YesNo)
        If Result = DialogResult.Yes Then
            IPList.Remove(IPList.Find(AddressOf FindItem))
        End If
        File.WriteAllLines(FilePath, IPList, Encoding.Default)
        For i = 0 To 300000
    End Sub
    Private Function FindItem(ByVal s As String)
        If s.Contains(ListView1.SelectedItems(0).Text) Then
            Return True
            Return False
        End If
    End Function
End Class

With this code when you click on an item, a messagebox will ask you to confirm first, then a new hosts file is written and the listview updated.

Thabk you tinstaafl but there is an error on this line of code.

File.WriteAllLines(FilePath, IPList, Encoding.Default)

the system underline this code


and says value of type(system.Collections.Generatic.List(OfString) 'cannot be converted to '1-dimmantional array of String.)

and my othere question based on your code I saw that when I make that line of code that is giving me an error and run the application I saw that you used the System drawing and I've never used that before my question is how then do I add Items in the fields and also I want the application to be editable on runtime, mean when the application is running and let say I want to add another Iterm that is not there and the application writes it to the Host file.

and says value of type(system.Collections.Generatic.List(OfString) 'cannot be converted to '1-dimmantional array of String.)

My system doesn't reproduce that error. I even took the code from here and pasted it into an empty form and it ran properly, without any modifications.

I saw that you used the System drawing and I've never used that before

If I'm not mistaken System.Drawing is the class used to draw the controls onto the form. You've probably been using it all along it's just been hidden.

then do I add Items in the fields

This is the relevant statement,ListView1.Items.Add(Ln(i)).SubItems.Add(Ln(0))The Items collection refers to the first column, and the subitems refer to all the columns. So in essence the value of subitem(0) for item(1) equals the value of item(1). This is important because the actually subitems end up being 1-based index and not 0-based index.

application writes it to the Host file.

Put this code in a function:

File.WriteAllLines(FilePath, IPList, Encoding.Default)
For i = 0 To 300000

and call it whenever you want to update the file from the list and the listview from the file. Just a note, the for loop is to allow time for the file to be written you may have to adjust that a bit to fine tune it.

when the application is running and let say I want to add another Iterm that is not there

I would suggest a generic dialog with a masked textbox, try mask 000.000.000 for the ip and a textbox for the address. Start the dialog with a button, and in the click event read the result of the dialog.showdialog() method. if the result is OK then get the values of the controls in the dialog before you close it, and add them to the list, and run your update function.

Thank you but this error is still showing and I noticed that when you were writing these codes you wrote them on a 3rd Form which is Form3 then I tried and load 3 forms and I copy these codes as they are and pasted them but still Can you use maybe the visual tools mean like the tools or listBox that you will load it from tools maybe I will be able to follow and maybe identify the problem that course this error Please note that I'm new in Vb and I'm just trying my best to understand it. Thank you

Thank you so mach for your help thank you I now manage to solve this problem of removing the address on a host file thank you and I will be glad if Tinstaafl you will please show me how to used those codes but thank you the problem has been solved.

actually, that function delete our host file completly, i wanna just change that content in previous programme. like first time i have entered the site in text box.. (www.facebook.com) , now second time i want to allow the computer to access that site. So, any source code to which remove textbox content from host file............ ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.