Sunday, July 10, 2005

Tail

On unix there are tons of little tools that are useful when working on a program. Tail shows the end of a file and tail -f will watch the file for changes and show them. This makes tail very yseful for watching file that are being written out to disk like logs files. I wanted a simple version of this tool for windows so I wrote one in VB.Net yesterday.


You can download the program from http://mysunfire.com/Downloads/tail.zip

The code for this program is very simple. It consists of a new win form project with a textbox set to dock fill.


Private FilePath As String
Private FileName As String
Private WithEvents Watcher As IO.FileSystemWatcher

Private Sub frmTail_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
'Open Dialog to ask for file to tail
Dim diag As New OpenFileDialog
diag.InitialDirectory = "c:\"
diag.ShowDialog()
FilePath = diag.FileName

'Show File
ShowFile()

'Set up file watcher
Watcher = New IO.FileSystemWatcher(FilePath.Substring(0, FilePath.LastIndexOf("\") + 1))
Watcher.EnableRaisingEvents = True

'Sub string off file name
Filename = FilePath.Substring(FilePath.LastIndexOf("\") + 1)

Catch ex As Exception
MessageBox.Show("Error Opening file!")
Me.Close()
End Try
End Sub

Private Sub Watcher_Changed(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles Watcher.Changed, Watcher.Deleted, Watcher.Created
'if file have changed then reload it
If e.Name = Filename Then
ShowFile()
End If
End Sub

Private Sub ShowFile()
Try
'Wait for the file to finish being saved byh other program
Threading.Thread.Sleep(10)

'Open file reader and load the end of the file
Dim rdr As New IO.StreamReader(FilePath)
Dim text As String = rdr.ReadToEnd
If text.Length > 10000000 Then
text = text.Substring(text.Length - 10000000)
End If

'Store it to the text box
txtFile.Text = text
rdr.Close()

'Scroll to the end so the bottom is always shown
txtFile.Select(txtFile.Text.Length, 0)
txtFile.ScrollToCaret()
Catch ex As Exception
'If the file was not accessable for what ever reason
End Try
End Sub

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home