Vb.net 在Visual Basic 2010中删除txt文件中两个标记之间的文本
我正在用VisualBasic2010制作一个应用程序,它允许我为我的XAMPP本地托管站点轻松创建.dev网址 到目前为止,我已经设法添加到必要的文件中,但没有删除 我需要一种方法来删除txt文件中两个标记之间的所有文本。例如:Vb.net 在Visual Basic 2010中删除txt文件中两个标记之间的文本,vb.net,visual-studio-2010,Vb.net,Visual Studio 2010,我正在用VisualBasic2010制作一个应用程序,它允许我为我的XAMPP本地托管站点轻松创建.dev网址 到目前为止,我已经设法添加到必要的文件中,但没有删除 我需要一种方法来删除txt文件中两个标记之间的所有文本。例如: 120.0.0.1 localhost 120.0.0.1 alsolocalhost ##testsite.dev#start# 127.0.0.1 testsite.dev ##testsite.dev#stop# ##indevsite.d
120.0.0.1 localhost
120.0.0.1 alsolocalhost
##testsite.dev#start#
127.0.0.1 testsite.dev
##testsite.dev#stop#
##indevsite.dev#start#
127.0.0.1 indevsite.dev
##indevsite.dev#stop#
我想删除##testsite.dev#start#和##testsite.dev#stop#标记之间的所有文本,以及删除标记本身
在我的visual basic代码中,这是我迄今为止所拥有的:
Sub removeText(ByVal siteName)
Dim fileName As String = "hosts.txt"
Dim startMark As String = "##" + siteName + "#start#"
Dim stopMark As String = "##" + siteName + "#stop#"
'Code for removing text...
End Sub
我现在所需要的就是能够删除我想要的文本,而不必触摸任何其他文本(这包括不要弄乱它的格式)。如果文件不太大,您可以将整个内容读取到一个字符串,然后像这样删除:
Dim siteName As String = "testsite.dev"
Dim fileName As String = "hosts.txt"
Dim startMark As String = "##" + siteName + "#start#"
Dim stopMark As String = "##" + siteName + "#stop#"
Dim allText As String = IO.File.ReadAllText(fileName)
Dim textToRemove = Split(Split(allText, startMark)(1), stopMark)(0)
textToRemove = startMark & textToRemove & stopMark
Dim cleanedText = allText.Replace(textToRemove, "")
IO.File.WriteAllText(fileName, cleanedText)
使用通常的方法,您可以通过以下方式实现您的目标:
Dim startmark, stopmark As String
Dim exclude As Boolean = False
Using f As New IO.StreamWriter("outputpath")
For Each line In IO.File.ReadLines("inputpath")
Select Case line
Case startmark
exclude = True
Case stopmark
exclude = False
Case Else
If Not exclude Then f.WriteLine()
End Select
Next
End Using
完成后,删除“旧”文件并重命名新文件。全部读取,制作备份副本,然后逐行写入,检查当前块状态(内部/外部)
您需要删除这两个标记的完整行吗?@TimSchmelter我想删除这两个标记以及它们之间的所有内容。您不能从文本文件中删除任何内容(尽管您可能会覆盖部分内容)。通常的方法是读取文件,处理内容,然后写一个新文件,或者用更改的内容覆盖旧文件。@igrimpe是否可以不使用任何内容或空格覆盖所选文本?这不是我想要的,但这个答案为我指明了正确的方向。
Sub removeText(ByVal siteName)
Dim fileName As String = "hosts.txt"
Dim startMark As String = "##" + siteName + "#start#"
Dim stopMark As String = "##" + siteName + "#stop#"
' A backup first
Dim backup As String = fileName + ".bak"
File.Copy(fileName, backup, True)
' Load lines from the source file in memory
Dim lines() As String = File.ReadAllLines(backup)
' Now re-create the source file and start writing lines not inside a block
Dim insideBlock as Boolean = False
Using sw as StreamWriter = File.CreateText(fileName)
For Each line As String in lines
if line = startMark
' Stop writing
insideBlock = true
else if line = stopMark
' restart writing at the next line
insideBlock = false
else if insideBlock = false
' Write the current line outside the block
sw.WriteLine(line)
End if
Next
End Using
End Sub