0

我试图删除文本文件中“X”行之后的所有行,我的意思是保留第一个“X”行并删除其余行。

我知道如何通过这种方式做到这一点:

1. Open the textfile
2. Read line by line
3. Count the line number.
4. Store the line content and append the string in the new textfile
5. Continue reading the next line and doing the same (step 3 & 4).
6. When line-count reaches "X" then stop reading lines.

太多的步骤和缓慢的方法,有人知道更好的改进(快速)方法来保留文本文件的前 1.000 行并删除其余行吗?

Private Sub Resize_LogFile()
    If File.ReadAllLines(LogFile).Length > 1000 Then
        ' Delete all the lines after line number: 1.000
        ' Save it
    End If
End Sub
4

3 回答 3

1

以下代码对我有用:

    Using fs As New FileStream(fileName, FileMode.Open)
        Dim pos As Long = 0

        Using sr As New StreamReader(fs)
            For i As Integer = 1 To maxNumOfLines
                Dim line As String = sr.ReadLine()
                pos += line.Length + 2
            Next

            fs.SetLength(pos - 2)
        End Using
    End Using
于 2013-05-20T18:45:04.530 回答
1

如果要在原地编辑文件,请先通读 X 行以找出第 X 行的末尾在哪里,然后在该位置截断文件。此解决方案永远不会引用超过一行的文件,因此不会为较大的文件占用更多内存。但是,较大的文件需要更多时间。

Using fs As New FileStream(Logfile, FileMode.Open)
    Using sr As New StreamReader(fs)
        For i As Integer = 1 To X
            sr.ReadLine() 'Read X lines
        Next
    End Using
    fs.SetLength(fs.Position) 'Remove all following text
End Using

但是,如果您想使用新文件,那么您的算法是最好的,因为行尾位置的不可预测性。

于 2013-05-20T17:56:08.363 回答
0

找到了这个并做了一些修改,我认为这是一个更好(最快)的解决方案:

不需要“For”,所以应用程序不会挂起,我很高兴 :)

Private Sub Resize_LogFile()
    Dim MaxLogEntries As Int32 = 1000
    Dim MinLogEntries As Int32 = 500
    If File.ReadAllLines(LogFile).Length > MaxLogEntries Then

        Dim strArray() As String = File.ReadAllLines(LogFile)
        Array.Reverse(strArray)
        ReDim Preserve strArray(MinLogEntries)
        Array.Reverse(strArray)
        Using WriteLogFile As New IO.StreamWriter(LogFile, False, Encoding.Default) : WriteLogFile.WriteLine(String.Join(vbNewLine, strArray)) : End Using

    End If
End Sub
于 2013-05-20T19:29:21.610 回答