我有一个文本文件(其主机文件) 我可以通过文本框将线(域)添加到文件中。 当我单击“保存”按钮时,输入的值(域)将以127.0.0.1前缀保存到文本(主机)文件中。同时它也在列表框中显示(在列表框中显示时,它不会显示前缀(127.0.0.1)。它只会显示从文本字段中获得的值)
我现在需要的是
当我单击并从列表框中选择一个项目并按“删除”按钮时,需要将其从列表框和文本(主机)文件中删除。
此外,在从列表框中删除所选项目时,还应从文件中删除前缀(127.0.0.1),而不能留空行。
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles BtnCustomDomainremove.Click
ListBox1.Items.Remove(ListBox1.SelectedItem)
Dim delLine As Integer = 1
Dim lines As List(Of String) = System.IO.File.ReadAllLines("C:\Windows\System32\drivers\etc\hosts").ToList
lines.RemoveAt(delLine - 1)
System.IO.File.WriteAllLines("C:\Windows\System32\drivers\etc\hosts", lines)
MessageBox.Show("URL removed from Block List !", "Custom Block List")
End Sub
上面的代码将文件中的最高值删除,并从列表框中选择一个值。
答案 0 :(得分:1)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lines As List(Of String) = System.IO.File.ReadAllLines("C:\Windows\System32\drivers\etc\hosts").ToList
Dim Findstring = IO.File.ReadAllText("C:\Windows\System32\drivers\etc\hosts")
Dim Lookfor As String = CStr("127.0.0.1" + ListBox1.SelectedItem)
If lines.Contains(Lookfor) Then
For i = 0 To Findstring.Length - 1
lines.Remove(Lookfor)
Next
System.IO.File.WriteAllLines("C:\Windows\System32\drivers\etc\hosts", lines)
ListBox1.Items.Remove(ListBox1.SelectedItem)
MessageBox.Show("URL removed from Block List !", "Custom Block List")
Else
MsgBox("string not found")
End If
End Sub
此代码对我有用,您可能需要对其稍加调整以匹配您的喜好,但是,似乎发现listbox1
中所选项目的每一次出现(如果有多个)(如果只有一个)发生时,您可以删除for
循环。
答案 1 :(得分:0)
代替对列表的每次更改读取和写入文件,在窗体关闭时保存列表。表单打开时读取文件并填充列表。打开表单后,只需照常添加和删除列表项即可。
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim path = "C:\Windows\System32\drivers\etc\hosts.txt"
Dim lines() As String = File.ReadAllLines(path)
'Substring(9) the characters in "127.0.0.1" are index 0-8 so we begin with index 9
'and return the rest of the string.
Dim TrimmedList = From line In lines
Select line.Substring(9)
For Each item In TrimmedList
ListBox2.Items.Add(item)
Next
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Dim sb As New StringBuilder()
For Each item In ListBox2.Items
sb.AppendLine("127.0.0.1" & item.ToString)
Next
Dim path = "C:\Windows\System32\drivers\etc\hosts.txt"
File.WriteAllText(path, sb.ToString)
End Sub
需要
Imports System.IO
Imports System.Text
答案 2 :(得分:-1)
尝试此代码
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles BtnCustomDomainremove.Click
ListBox1.Items.Remove(ListBox1.SelectedItem)
Dim details As String = ""
For Each o As Object In ListBox1.Items
details += o.ToString + vbNewLine
Next
My.Computer.FileSystem.WriteAllText("C:\Windows\System32\drivers\etc\hosts", details, False)
MessageBox.Show("URL removed from Block List !", "Custom Block List")
End Sub