【发布时间】:2010-01-20 06:44:56
【问题描述】:
我看过有关从文本文件中删除指定为函数参数的行的帖子,但我只需要从文件中删除第一行和最后一行。
在处理文件方面我仍然是新手,但删除第一行似乎应该很简单......只需删除从 BOF 到第一个 CrLf 字符的所有文本。我说的对吗?
至于最后一行,我知道我必须计算文本文件中的行数才能找到它(因为文件并不总是 x 行长)。这是我真正需要帮助的地方。
注意我正在使用 VB.NET 2005
【问题讨论】:
我看过有关从文本文件中删除指定为函数参数的行的帖子,但我只需要从文件中删除第一行和最后一行。
在处理文件方面我仍然是新手,但删除第一行似乎应该很简单......只需删除从 BOF 到第一个 CrLf 字符的所有文本。我说的对吗?
至于最后一行,我知道我必须计算文本文件中的行数才能找到它(因为文件并不总是 x 行长)。这是我真正需要帮助的地方。
注意我正在使用 VB.NET 2005
【问题讨论】:
将文件完全作为字符串读入行列表。使用索引循环将文件写回以捕获除第一个和最后一个项目之外的所有项目。
Dim listText As New List(Of String)
Dim objLine As String = ""
Using objReader As StreamReader = New StreamReader("c:\test.txt")
Do
objLine = objReader.ReadLine()
If objLine IsNot Nothing Then listText.Add(objLine)
Loop Until objLine Is Nothing
End Using
Using objWriter As StreamWriter = New StreamWriter("c:\testOutput.txt")
For I As Integer = 1 To listText.Count - 2
objWriter.WriteLine(listText.Item(I))
Next
End Using
编辑以满足非常挑剔的人:
Dim arrText() As String
Dim sLine As String = ""
arrText = File.ReadAllLines("c:\test.txt")
Using objWriter As StreamWriter = New StreamWriter("c:\testOutput.txt")
For I As Integer = 1 To arrText.Length - 2
objWriter.WriteLine(arrText(I))
Next
End Using
【讨论】:
System.IO.File 上的File.ReadAllLines 方法:)
这是删除最后一行,而不读取整个文件。您可能需要修改逻辑以说明 EOF 是换行符...
Dim fs As New FileStream("c:\test.txt", FileMode.Open, FileAccess.ReadWrite)
Dim b(1) As Byte
Do
fs.Seek(fs.Length - 2, SeekOrigin.Begin) 'seek 2 bytes from EOF
fs.Read(b, 0, 2) 'read last two bytes
'are they newline
If System.Text.Encoding.ASCII.GetString(b, 0, 2) <> Environment.NewLine Then
fs.SetLength(fs.Length - 1) 'set length to -1
Else
fs.SetLength(fs.Length - 2)
Exit Do
End If
Loop
fs.Close()
【讨论】:
文件是流,没有捷径。您必须读取整个文件并将其写回,减去第一行和最后一行。当然,效率极低,请改用数据库。
【讨论】: