2012-11-17 53 views
1

我在Visual Basic 2010中創建了一個應用程序,該應用程序允許我輕鬆地爲我的XAMPP本地託管網站創建.dev Web地址。刪除Visual Basic 2010中兩個標記之間的txt文件中的文本

到目前爲止,我已經設法添加到必要的文件,但不能刪除。

我需要一種方法來刪除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#之間的文本開頭#和###testsite.dev停止#標記,以及移除標記自己。

在我的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 

所有我現在需要的是能夠去除我想要的文字,不接觸任何其他文字(這包括不搞亂它的格式化)。

+0

你需要刪除這兩個標誌的完整產品線? –

+0

@TimSchmelter我想刪除標記以及它們之間的所有內容。 – Tam

+0

你不能從文本文件中刪除任何東西(儘管你可能會覆蓋它的一部分)。正常的方法是讀取文件,處理內容,然後編寫新文件或使用更改後的內容覆蓋舊文件。 – igrimpe

回答

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 
+0

完美的作品,謝謝! – Tam

+0

不是我正在尋找的東西,但是這個答案指出了我正確的方向。 – Malachi

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) 
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 

完成後,刪除「舊」文件並重命名新文件。

相關問題