1

我在 Visual Basic 2010 中制作了一个应用程序,它可以让我轻松地为我的 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.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

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

4

3 回答 3

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
于 2012-11-17T00:26:09.963 回答
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)
于 2012-11-17T00:22:17.477 回答
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

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

于 2012-11-17T00:22:47.650 回答