Saturday, October 4, 2008

Open a directory of text files and display them in a text box

It is always handy to be able to view a bunch of output files one after
another without having to open them all in a tabbed editor or open a
bunch of notepads. On a form named MainForm, add buttons Named:
LoadOutputFiles, NextFile and PreviousFile; add a label named
OutputPosition; Copy and paste the code below...

Dim OutputFiles as String()
Dim LoadedID as Integer
Dim TotalNumberOfFilesLoaded as Integer

Public Class MainForm

Private Sub LoadOutputFiles_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles LoadOutputFiles.Click
If Not FolderBrowserDialog.SelectedPath.Length > 1 Then
If Not FolderBrowserDialog.ShowDialog =
Windows.Forms.DialogResult.OK Then
Exit Sub
End If
End If
OutputFiles =
System.IO.Directory.GetFiles(FolderBrowserDialog.SelectedPath) 'Add a
filter to the 'GetFiles' function for *.txt etc...
TotalNumberOfFilesLoaded = OutputFiles.Length
Array.Sort(OutputFiles) 'Sort the Files
LoadedID = 0
ReadNextFile(LoadedID)
End Sub

Sub ReadNextFile(ByVal ID As Integer)
If OutputFiles Is Nothing Then
Exit Sub
End If
If ID = TotalNumberOfFilesLoaded Or ID >
TotalNumberOfFilesLoaded Then
ID = 0
LoadedID = 0
End If
If ID = -1 Then
ID = TotalNumberOfFilesLoaded - 1
LoadedID = TotalNumberOfFilesLoaded - 1
End If
Dim fs As IO.StreamReader = Nothing
Try
fs = New System.IO.StreamReader(OutputFiles(ID))
OutputText.Text = fs.ReadToEnd
fs.Close()
Catch ex As Exception
If Not fs Is Nothing Then
fs.Close()
End If
End Try
OutputPosition.Text = String.Format("{0} of {1}", LoadedID + 1,
TotalNumberOfFilesLoaded)
End Sub


Private Sub NextFile_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles NextFile.Click
LoadedID -= 1
ReadNextFile(LoadedID)
End Sub

Private Sub PreviousFile_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles PreviousFile.Click
LoadedID += 1
ReadNextFile(LoadedID)
End Sub

End Class

No comments: