我正在为学校项目制作客户管理系统,我需要能够删除客户。 每个客户在文本文件中占用8行。
我用它来删除一行:
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 :(得分:0)
而不是for-each-loop,我会使用经典的for-next,步长为8 - 如果我们可以确定每个数据集由8行组成,并且searchstring在第一个中找到:< / p>
...
For LineNo As Integer=0 to lines.count()-1 step 8
If lines(LineNo).Contains(searchstring1) = False
...
End If
Next lineNo
此外,您应该在进入for循环之前直接关闭输入文件,并且您应该在完成for-next-loop之后才编写输出行,否则您将在搜索后删除所有客户
下一步是检查文件操作期间可能发生的错误......
答案 1 :(得分: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
另一个解决方案是,通过操作for-var-counter跳过接下来的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
它将避免必要的迭代和Ifs ..
答案 2 :(得分: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