如何在Visual Basic中从文本文件中删除第一行和最后一行 [英] How to delete the first and last lines from a text file in visual basic
问题描述
我已经看到有关从文本文件中删除指定为功能参数的行的帖子,但是我只需要删除文件中的第一行和最后一行.
I've seen posts on deleting the lines from a text file that are specified as a function parameter, but I only need to delete the first and last lines from the file.
在处理文件时,我还是一个新手,但是删除第一行似乎很简单...只需删除BOF中所有文本到第一个CrLf字符.我说的对吗?
I'm still a newbie when it comes to working in files, but it seems that it should be simple to delete the first line... Just delete all text from BOF to the first CrLf character. Am I right?
对于最后一行,我知道我必须对文本文件中的行数进行计数才能找到它(因为文件不一定总是x行长).这是我真正需要帮助的地方.
As for the last line, I understand that I'll have to get a count of the lines in the text file to find it (as the file won't always be x amount of lines long). This is where I really need some help.
我正在使用VB.NET 2005
N.B. I'm using VB.NET 2005
推荐答案
将文件完全读取为字符串形式的行列表.使用索引循环将文件写回,以捕获除第一项和最后一项以外的所有内容.
Read the file in to a list of lines as string completely. Write the file back out using an indexed loop to capture all but the first and last items.
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
编辑以满足非常挑剔的要求
Edit to satisfy the very picky:
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
这篇关于如何在Visual Basic中从文本文件中删除第一行和最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!