我正在尝试删除所选行,然后将其余行保存到文件中。但是,当我保存它时,它会完全清空文件。
Console.Write("Please eneter the first name of the student you wish to search for: ")
searchfname = Console.ReadLine
searchfname = StrConv(searchfname, VbStrConv.ProperCase)
Console.Write("Please enter the second name of the student you wish to search for: ")
searchsname = Console.ReadLine
searchsname = StrConv(searchsname, VbStrConv.ProperCase)
Dim foundItem() As String = Nothing
Dim foundline As String = Nothing
Dim fnsearch As String = String.Join(searchfname, searchsname)
Dim lines As New List(Of String)(File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv"))
For Each line As String In lines
If searchfname = item(3) And searchsname = item(4) Then
Console.WriteLine(line)
Console.WriteLine()
Console.WriteLine("Are you sure you wish to delete this record? (y/n)")
End If
Dim answer As String
answer = Console.ReadLine
If answer = "y" Or answer = "Y" Then
Console.Clear()
lines.Remove(line)
Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
sw.WriteLine(lines.ToString)
End Using
ElseIf answer = "n" Or answer = "N" Then
staffmenu()
End If
Next
答案 0 :(得分:2)
方法List(Of T).ToString
不会生成包含集合元素的值。相反,它只会返回类型名称。
您要查找的API是File.WriteAllLines
。使用此代替StreamWriter
和Using
块
File.WriteAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv", lines)
答案 1 :(得分:2)
在代码中查看此行:
sw.WriteLine(lines.ToString)
从该语句中提取lines.ToString
表达式。该表达式的结果是“System.String
”。您告诉流编写器将文本“System.String”写入文件。
要修复它,你需要更像这样的东西:
Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
For Each line As String In lines
sw.WriteLine(line)
Next line
End Using
答案 2 :(得分:1)
我可以看到这个问题可以从给定的答案和评论中解决,但我想在写入文件时添加一个使用Join函数的替代方法。尝试这样可能会有所帮助:
Using sw As New StreamWriter(.....)
sw.WriteLine(Join(lines.ToArray(), Environment.NewLine))
End Using
由于使用VB.Net,这是一个vb.net特定的解决方案,不能在C#中使用。对于C#,请改用string.join。
希望它也有帮助!