Alex
Alex

Reputation: 2111

vb.net how to loop through a directory listing?

How can I loop through a folder getting each file listed and when its date/time?

Upvotes: 19

Views: 107214

Answers (3)

schlebe
schlebe

Reputation: 3716

we have the chance to develop in VB.Net (not in Java) and some variable's definitions can be shortened.

I still use GetFiles() and I have added the code to display the DateTime infos.

Imports System
Imports System.IO
...
Dim dir As New DirectoryInfo(sFolderName)
For Each f In dir.GetFiles()
    Console.WriteLine(">> FILE-NAME: [" & f.Name & "]")
    Console.WriteLine(">> UPDATE-DATE: " & f.lastWriteTime.toString("yyyy-MM-dd"))
    Console.WriteLine(">> CREATE-DATE: " & f.creationTime.toString("yyyy-MM-dd"))
Next

Upvotes: 2

 For Each LogFile In Directory.GetFiles(Application.StartupPath & "\Txt\")

        ' do whatever wtih filename

    Next

Upvotes: 5

micahtan
micahtan

Reputation: 19160

Use DirectoryInfo.GetFiles() and extract the data (Name, CreationTime, etc.) from the FileInfo class.

I've pasted some code from the MSDN page here.

Imports System
Imports System.IO
Public Class GetFilesTest
    Public Shared Sub Main()
        ' Make a reference to a directory.
        Dim di As New DirectoryInfo("c:\")
        ' Get a reference to each file in that directory.
        Dim fiArr As FileInfo() = di.GetFiles()
        ' Display the names of the files.
        Dim fri As FileInfo
        For Each fri In fiArr
            Console.WriteLine(fri.Name)
        Next fri
    End Sub 'Main
End Class 'GetFilesTest

Upvotes: 46

Related Questions