2014-04-13 49 views
0

我正在爲學校項目制定客戶管理系統,我需要能夠刪除客戶。 每個客戶在文本文件中佔用8行。VB.NET - 如何刪除文本文件中的多個連續行?

我已經得到了用它來刪除一行:

Dim lines() As String 
Dim outputlines As New List(Of String) 
Dim searchstring1 As String = lblName.Text 
lines = IO.File.ReadAllLines("Customers.text") 
For Each line As String In lines 
    If line.Contains(searchstring1) = False Then 
     outputlines.Add(line) 
     FileClose(1) 
     System.IO.File.Delete("Customers.text") 
     IO.File.WriteAllLines("Customers.text", outputlines) 
     FileClose(1) 
    End If 
Next 

但我不知道如何將這種重複另一個7倍,任何想法?

回答

0

而不是每個循環,我會使用經典的for-next,步驟爲8 - 如果我們可以確定每個數據集由8行組成,並且searchstring在第一行中找到:

... 
For LineNo As Integer=0 to lines.count()-1 step 8 
    If lines(LineNo).Contains(searchstring1) = False 
     ... 
    End If 
Next lineNo 

另外,你應該再進for循環讀取後直接關閉輸入文件,你應該寫outputlines的換下一循環完成後才能,否則將刪除所有客戶搜索後的一個。

下一步是檢查這可以在文件操作發生錯誤...

0

如果你的文件已混合格式,並且不能使用Step 8,因爲它不包含數據的唯一N-8-行,你可以使用一個櫃檯。
找到客戶並在每個循環中遞減時將其設置爲8。
在輸出文件中創建新行將僅在counter = 0時生成。

Dim countMatchingLines As Integer = 0 
For Each line As String In lines 
    If line.Contains(searchstring1) Then 
     countMatchingLines = 8 
    End If 

    If countMatchingLines = 0 Then 
     outputlines.Add(line) 
     FileClose(1) 
     System.IO.File.Delete("Customers.text") 
     IO.File.WriteAllLines("Customers.text", outputlines) 
     FileClose(1) 
    Else 
     countMatchingLines -= 1 
    End If 
Next 

另一種解決方案,只是通過操縱用於-VAR櫃檯跳過下一個8行:

For i as Integer = 0 to lines.Count() - 1 
    If line.Contains(searchstring1) Then 
     i = Math.Min(i + 8, lines.Count()-1) 
    Else 
     outputlines.Add(line) 
     FileClose(1) 
     System.IO.File.Delete("Customers.text") 
     IO.File.WriteAllLines("Customers.text", outputlines) 
     FileClose(1) 
    End If 
Next 

這將避免必要的迭代和If ..

+0

非常感謝你的工作! – user3529184

0

試試這個...

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Label1.Text = RemoveParagraphOfText("GARBAGE RECORD", Line) 
End Sub 

Public Function RemoveParagraphOfText(ByVal textTobeRemoved As String, ByVal Message As String) As String 
    RemoveParagraphOfText = Message.Replace(textTobeRemoved, "") 
End Function 
相關問題