[英]How to delete the line at the end of the text file in 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
,使用 boolean 變量來了解您是否已添加第一行,如果已添加第一行,請在添加內容之前使用帶有空字符串的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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.