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 に答える
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 に答える