在Visual Basic 2010中删除两个标记之间的txt文件中的文本

时间:2012-11-17 00:05:45

标签: vb.net visual-studio-2010

我正在Visual Basic 2010中创建一个应用程序,这将允许我轻松地为我的XAMPP本地托管站点创建.dev Web地址。

到目前为止,我已设法添加到必要的文件,但不删除。

我需要一种方法来删除txt文件中两个标记之间的所有文本。例如:

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#markers之间的所有文本,以及删除标记本身。

在我的视觉基本代码中,这是我到目前为止所拥有的:

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

我现在需要的是能够删除我想要的文本而不触及任何其他文本(这包括不弄乱它的格式化)。

3 个答案:

答案 0 :(得分:2)

全部读取,制作备份副本,然后逐行检查当前阻止状态(内部/外部)

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

答案 1 :(得分:1)

如果文件不是很大,你可以把整个东西读成一个字符串然后删除:

    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)

答案 2 :(得分:0)

使用通常的方式,您可以通过以下方式实现目标:

    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

完成后,删除“旧”文件并重命名新文件。