CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Icomparer and sorting by file dates

  1. #1
    Join Date
    Dec 2009

    Icomparer and sorting by file dates

    I'm using Visual Studio .Net 2008 on Vista. The goal of my program is to watch a directory, get file information, then sort them by thier date, and produce a updated text file. I can't seem to get my code to generate a list of files sorted by date. The code does produce a general list of files, however presently ordered in the directory. I also tried an alternate way of sorting the files by date by creating a string, removing the date using substring, then comparing the file dates using datetime.parse but it produces a exception error. My first method using the structure follows:
    Public Class Form1
        Private Const outputloc As String = "C:\tickercontent.txt"
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim dname As String = "M:\"
            ShowFiles(dname, outputloc)
            ' Get the Path to watch
            FileSystemWatcher1.Path = dname
            FileSystemWatcher1.IncludeSubdirectories = False
            FileSystemWatcher1.Filter = "*.*"
            ' Make the FileSystemWatcher.
            FileSystemWatcher1.NotifyFilter = 0
            FileSystemWatcher1.NotifyFilter = FileSystemWatcher1.NotifyFilter Or NotifyFilters.FileName
            FileSystemWatcher1.EnableRaisingEvents = True
        End Sub
        ' Create the structure for the file array
        Structure FilesStruct
            ' Dim startHTML As String
            Dim Text As String
            Dim fsize As String
            Dim Creation As String
            'Dim endHTML As String
        End Structure
        Private Sub WatcherHandler(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles FileSystemWatcher1.Created, FileSystemWatcher1.Changed
            ShowFiles(FileSystemWatcher1.Path, outputloc)
        End Sub
        ' Sort the files by date in the text file
        Sub SortFiles(ByVal FileList As Array)
        End Sub
        Sub ShowFiles(ByVal selFolder As String, ByVal outputpath As String)
            Dim objWriter As New System.IO.StreamWriter(outputpath)
            Dim Text As String
            Dim files() As String
            Dim FileList As New ArrayList
            Dim file As String
            Dim fsize As String
            Dim totalfiles As Integer = 0
            Dim sumsizefiles As Integer
            Dim creation As String
            Dim DirInfo As String
            Dim FI As IO.FileInfo
            Dim line As String
            ' Get the files in the selected folder/directory
            files = IO.Directory.GetFiles(selFolder)
            ' Get sub directories subdirs now contains a list of directories under selFolder
            Dim subdirs As New ArrayList
            GetDirectories(selFolder, subdirs)
            ' Write HTML Dive message start tage
            objWriter.WriteLine("<div class=""message"">")
            RichTextBox1.Text = "<div class=""message"">"
            ' Get Directory Information
            DirInfo = Path.GetDirectoryName(selFolder)
            ' Write the directory information to the selected output file location/objWriter
            objWriter.WriteLine("Directory of " + DirInfo + "</BR>")
            RichTextBox1.Text = "Directory of " + DirInfo + "</BR>"
            For Each file In files
                ' Create new file object with FileStruct's structure
                Dim newfile As New FilesStruct
                ' Create FileInfo object
                FI = New IO.FileInfo(file)
                ' Get the total sum of files found during the loop
                totalfiles = totalfiles + 1
                ' Get the file's length in byte's
                fsize = FI.Length.ToString("#,###")
                ' Get the file's creation time
                creation = FI.CreationTime
                ' Get the file's total size
                sumsizefiles += FI.Length / 1024
                ' Build array with pdf file names
                Text = IO.Path.GetFileName(file)
                ' Write to text file
                RichTextBox1.Text = Text
                line = Text & vbTab & fsize & vbTab & creation + "</BR>"
                objWriter.WriteLine(Text & vbTab & fsize & vbTab & creation + "</BR>")
                RichTextBox1.Text = Text & vbTab & fsize & vbTab & creation + "</BR>"
                ' Assign values to the ArrayList 
                newfile.Text = CStr(Text)
                newfile.fsize = CStr(fsize)
                newfile.Creation = CStr(creation)
                ' Store the collection of items in the ArrayList
            ' Sort the array
            Dim sorted As Boolean = True
            Dim DateComparer As New CustomDateComparer
                FileList.Sort(New CustomDateComparer)
            Catch SortException As InvalidOperationException
                MsgBox("You can't sort an ArrayList whose items " & _
                       "aren't of the same type.")
            Catch GeneralException As Exception
                MsgBox("The following exception occured: " & _
                       vbCrLf & GeneralException.Message)
                sorted = False
            End Try
            If sorted Then
                ' Print the ArrayList by extracting items
                sumsizefiles = sumsizefiles / 1024
                ' Print the summary information
                objWriter.WriteLine(CStr(totalfiles).ToString + " File(s) " + CStr(sumsizefiles) + " KB" + "</BR>")
                RichTextBox1.Text = CStr(totalfiles).ToString + " File(s) " + CStr(sumsizefiles) + " KB" + "</BR>"
                objWriter.WriteLine("Not including " + subdirs.Count.ToString + " Sub Directories" + "</BR>")
                RichTextBox1.Text = "Not including " + subdirs.Count.ToString + " Sub Directories" + "</BR>"
                RichTextBox1.Text = "</div>"
            End If
            ' Clear the ArrayList before the next execution of this program
        End Sub
        Sub GetDirectories(ByVal StartPath As String, ByRef DirectoryList As ArrayList)
            ' Get all sub directories in the startpath/selFolder
            Dim Dirs() As String = Directory.GetDirectories(StartPath)
            ' Add the new sub directory to the directory list
            ' Recursively, get the sub directories for each directory in the directory list
            For Each Dir As String In Dirs
                GetDirectories(Dir, DirectoryList)
        End Sub
    End Class
    Class CustomDateComparer : Implements IComparer
        Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
            Dim file1, file2 As Form1.FilesStruct
            ' Try to catch errors if the objects are of differing types
                file1 = CType(x, Form1.FilesStruct)
                file2 = CType(y, Form1.FilesStruct)
            Catch CompareException As System.Exception
                Throw (CompareException)
                Exit Function
            End Try
            ' Begin Comparison 
            If file1.Creation < file2.Creation Then
                Return -1
                If file1.Creation > file2.Creation Then
                    Return 1
                    Return 0
                End If
            End If
        End Function
    End Class
    The code doesn't generate an error, and I don't know why it's not working. Any clues? Anyone, please help.
    Last edited by Cimperiali; February 18th, 2010 at 11:36 PM.

  2. #2
    Join Date
    Jan 2006
    Fox Lake, IL

    Re: Icomparer and sorting by file dates

    Please use CODE TAGS, so we can read your code.
    ' Like this

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)