删除一行后如何删除文本文件末尾的空行?

How to remove a blank line at the end of a text file after deleting a line?

我从 Stack Overflow 借用了四行代码,关于从 vb.net 中的文本文件中删除特定行。他们在这里:

 Dim delLine As Integer = 4
 Dim lines As List (Of String) = File.ReadAllLines ("c:\essai.librarie", Encoding.UTF8).ToList()
 lines.RemoveAt(delLine - 1)
 File.WriteAllLines("c:\outfile.librairie", lines, Encoding.UTF8)

它工作正常但是在删除我的第 4 行之后,我在文件的最后一个位置有一个空行,编号为 11! (见屏幕截图)。

如何避免这个空行?

File.WriteAllLines() add a line terminator - defined by the protected CoreNewLine 基础 class、TextWriter 中的字段,并由 TextWriter.NewLine 虚拟 属性 返回到它写入的每一行,包括最后一行。

你有不同的方法来删除这个终止符:

Imports System.IO

Dim sourcePath = Path.Combine([Source Path], "SomeFile.txt")
Dim destinationPath = Path.Combine([Dstination Path], "SomeOtherFile.txt")
Dim lineToDelete As Integer = 3

Dim lines As List(Of String) = File.ReadAllLines(sourcePath, Encoding.UTF8).ToList()
lines.RemoveAt(lineToDelete - 1)

▶ 简化方法,使用 File.WriteAllText() and rebuilding the Lines with String.Join():

File.WriteAllText(destinationPath, String.Join(Environment.NewLine, lines), Encoding.UTF8)

String.Join() 不会将分隔符添加到数组中的最后一个元素。

▶ 将 StreamWriter, looping the lines in the array to the one before the last, then change the line terminator, setting the TextWriter.NewLine 属性 用于空字符串(而非空字符):

Using stream As New StreamWriter(destinationPath, False, Encoding.UTF8)
    Dim index As Integer = 0
    For index = 0 To lines.Count - 2
        stream.WriteLine(lines(index))
    Next
    stream.NewLine = String.Empty
    ' index is set to the closure, lines.Count - 1
    stream.WriteLine(lines(index))
End Using

▶ 使用 File.WriteAllLines() - 这会将 NewLine 个字符添加到最后一行 - 然后使用 FileStream to remove the trailing chars by setting the length of the File, calling FileStream.SetLength():

[Stream].Length = [Stream].Length - [Line terminator].Length`

Stream.Length 设置为较低的值会截断文件。

File.WriteAllLines(destinationPath, lines, Encoding.UTF8)
Using fStream As New FileStream(destinationPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
    fStream.SetLength(fStream.Length - Environment.NewLine.Length)
End Using

▶ 使用 FileStream,写入 Encoding.UTF8.GetBytes() 返回的字节,为除最后一行之外的所有行添加行终止符:

Using fStream As New FileStream(destinationPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)
    Dim lastLine = lines.Count - 1
    For index As Integer = 0 To lines.Count - 1
        Dim line As String = lines(index) & If(index <> lastLine, Environment.NewLine, "")
        Dim bytes = Encoding.UTF8.GetBytes(line)
        fStream.Write(bytes, 0, bytes.Length)
    Next
End Using

还有更多...

请注意,您可以忽略它,因为当您回读它时:

 lines = File.ReadAllLines(destinationPath, Encoding.UTF8).ToList()

您不会在集合中找到空行。但是,当然,这取决于具体的用例(这些文件的用途)。