Anonymous
Anonymous

Reputation: 13

vb check for specific file type in dir and perform code

I'm trying to make a program that checks for specific file type in a directory, then executes a code if there are any files of that type found.

I'm assuming something like this:

For Each foundFile As String In
  My.Computer.FileSystem.GetFiles(My.Computer.FileSystem.SpecialDirectories.MyDocuments)

  (If any found files are, for example, "txt" files, then display their content.)
Next

Thanks in advance.

Upvotes: 0

Views: 153

Answers (2)

Mukul Varshney
Mukul Varshney

Reputation: 3141

Dim di As DirectoryInfo = New DirectoryInfo(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
For Each fi In di.GetFiles("*.txt")
    Dim content As String = My.Computer.FileSystem.ReadAllText(fi.FullName)
    Console.WriteLine(fi.Name)
Next

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460058

You can use Directory.GetFiles or Directory.EnumerateFiles with a parameter for the extension-filter:

Dim directoryPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim allTxtFiles = Directory.EnumerateFiles(directoryPath, ".txt") 
For each file As String In allTxtFiles
    Console.WriteLine(file)
Next

The difference between both methods is that the first returns a String(), so loads all into memory immediately whereas the second returns a "query". If you want to use LINQ it's better to use EnumerateFiles, f.e. if you want to take the first 10 files:

Dim firstTenFiles As List(Of String) = allTxtFiles.Take(10).ToList()

Upvotes: 1

Related Questions