What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleMake a log file with multiple overflow versions in Visual Basic .NET
DescriptionThis example shows how to make a log file with multiple overflow versions in Visual Basic .NET.
Keywordsfiles, versions, file versions, log file, overflow file, draw polygons, drawing, Visual Basic .NET, VB.NET
CategoriesFiles and Directories, Software Engineering
This program makes a log file named log.txt. When you write entries into it, the program checks the file's size. If the size exceeds 100 bytes (you would make this larger for a real application), the program renames the file log.txt.1 and starts a new log.txt. It bumps down older versions of the log to log.txt.2, and log.txt.3. This version usese 3 backup versions but you can also change that in a real application.

The WriteToLog method does all of the work.

' If the file exceeds max_size bytes, move it to a new file
' with .1 appended to the name and bump down older
' versions. (E.g. log.txt.1, log.txt.2, etc.)
' Then write the text into the main log file. 
Private Sub WriteToLog(ByVal new_text As String, ByVal _
    file_name As String, ByVal max_size As Long, ByVal _
    num_backups As Integer)
    ' See if the file is too big.
    Dim file_info As New FileInfo(file_name)
    If (file_info.Exists AndAlso file_info.Length > _
        max_size) Then
        ' Remove the oldest version if it exists.
        If (File.Exists(file_name & "." & _
            num_backups.ToString())) Then
            File.Delete(file_name & "." & _
        End If

        ' Bump down earlier backups.
        For i As Integer = num_backups - 1 To 1 Step -1
            If (File.Exists(file_name & "." & _
                i.ToString())) Then
                ' Move file i to file i + 1.
                File.Move(file_name & "." & i.ToString(), _
                     file_name & "." & (i + 1).ToString())
            End If
        Next i

        ' Move the main log file.
        File.Move(file_name, file_name & ".1")
    End If

    ' Write the text.
    File.AppendAllText(file_name, new_text & vbCrLf)
End Sub
The code first checks whether the file exists and whether its size exceeds the maximum allowed size. If so, it moves the logs around.

First the code deletes the oldest allowed backup log if it exists. It then bumps backup logs down so, for example, log.txt.2 becomes log.txt.3. It then moves the "live" log to log.txt.1.

The method finishes by appending the new text to the "live" log file. Note that File.AppendAllText automatically creates the file if it doesn't already exist.

Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.