如何解决如何删除vb.net中文本文件末尾的行?
如何确保文件末尾没有多余的行?有点特别,我把一行分成三个地方,分别是17、90和120字节(总共:227字节)。我试图用Write替换WriteLine,那很好,但之后我不能写新行了! 我当前的代码:
Dim bibliotheque As New article
With bibliotheque
.Title = TextBox1.Text
.Name = TextBox2.Text
.Charge = TextBox3.Text
End With
Dim fileName As String = "c:\essai.librairie"
Dim fs As FileStream = Nothing
Try
fs = New FileStream(fileName,FileMode.Append)
Using writer As StreamWriter = New StreamWriter(fs)
writer.WriteLine(bibliotheque.Title.PadRight(17," "c).ToString & bibliotheque.Name.PadRight(90," "c).ToString & bibliotheque.Charge.PadRight(120," "c).ToString)
ListBox1.Items.Add(bibliotheque.Name)
End Using
Finally
If fs IsNot Nothing Then
fs.Dispose()
End If
End Try
解决方法
您可以将 WriteLine
替换为 Write
,使用布尔变量来了解您是否已经添加了第一行,如果已经添加了第一行,请使用以下命令添加回车/换行符一个带有空字符串的 WriteLine
,在添加内容之前,如下所示:
Dim linesExist As Boolean = IO.File.ReadAllLines(fileName).Count > 0
Try
fs = New FileStream(fileName,FileMode.Append)
Using writer As StreamWriter = New StreamWriter(fs)
If linesExist Then writer.WriteLine()
writer.Write(bibliotheque.Title.PadRight(17," "c).ToString & bibliotheque.Name.PadRight(90," "c).ToString & bibliotheque.Charge.PadRight(120," "c).ToString)
ListBox1.Items.Add(bibliotheque.Name)
End Using
Finally
If fs IsNot Nothing Then
fs.Dispose()
End If
End Try
显然,File.ReadAllLines
可能会很慢,您可以使用更优化的方法来检测文件是否存在以及是否有内容,但它确实解决了手头的问题。
Dim fileName As String = "c:\essai.librairie"
Dim bt As New article With {
.Title = TextBox1.Text,.Name = TextBox2.Text,.Charge = TextBox3.Text
}
Using fs As New FileStream(fileName,FileMode.Append)
Using writer As New StreamWriter(fs)
If fs.Length > 0 Then writer.WriteLine()
writer.Write($"{bt.Title,-17}{bt.Name,-90}{bt.Charge,-120}")
End Using
End Using
ListBox1.Items.Add(bt.Name)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。