Directories in Visual Basic .NET

Here’s an idiomatic Visual Basic .NET example that demonstrates working with directories:

Imports System
Imports System.IO

Module DirectoryOperations
    Sub Main()
        ' Create a new sub-directory in the current working directory
        Dim subDirPath As String = Path.Combine(Environment.CurrentDirectory, "subdir")
        Directory.CreateDirectory(subDirPath)

        ' It's good practice to use Try...Finally for cleanup operations
        Try
            ' Helper function to create a new empty file
            Dim CreateEmptyFile = Sub(name As String)
                                      File.WriteAllText(name, "")
                                  End Sub

            CreateEmptyFile(Path.Combine(subDirPath, "file1.txt"))

            ' Create a hierarchy of directories
            Dim nestedDirPath As String = Path.Combine(subDirPath, "parent", "child")
            Directory.CreateDirectory(nestedDirPath)

            CreateEmptyFile(Path.Combine(subDirPath, "parent", "file2.txt"))
            CreateEmptyFile(Path.Combine(subDirPath, "parent", "file3.txt"))
            CreateEmptyFile(Path.Combine(nestedDirPath, "file4.txt"))

            ' List directory contents
            Console.WriteLine("Listing subdir/parent")
            For Each entry In Directory.GetFileSystemEntries(Path.Combine(subDirPath, "parent"))
                Dim info As New FileInfo(entry)
                Console.WriteLine($"  {info.Name} {If(info.Attributes.HasFlag(FileAttributes.Directory), "Directory", "File")}")
            Next

            ' Change current directory
            Directory.SetCurrentDirectory(nestedDirPath)

            Console.WriteLine("Listing current directory (subdir/parent/child)")
            For Each entry In Directory.GetFileSystemEntries(".")
                Dim info As New FileInfo(entry)
                Console.WriteLine($"  {info.Name} {If(info.Attributes.HasFlag(FileAttributes.Directory), "Directory", "File")}")
            Next

            ' Change back to original directory
            Directory.SetCurrentDirectory(Environment.CurrentDirectory)

            ' Recursively visit directory
            Console.WriteLine("Visiting subdir")
            VisitDirectory(subDirPath)

        Finally
            ' Clean up: remove the created directory and its contents
            Directory.Delete(subDirPath, True)
        End Try
    End Sub

    Sub VisitDirectory(path As String)
        For Each entry In Directory.GetFileSystemEntries(path)
            Dim info As New FileInfo(entry)
            Console.WriteLine($"  {info.FullName} {If(info.Attributes.HasFlag(FileAttributes.Directory), "Directory", "File")}")
            If info.Attributes.HasFlag(FileAttributes.Directory) Then
                VisitDirectory(entry)
            End If
        Next
    End Sub
End Module

This Visual Basic .NET example demonstrates various operations with directories:

  1. We use Directory.CreateDirectory to create new directories.
  2. Path.Combine is used to create path strings in a platform-independent way.
  3. We use a lambda expression (Sub) to create a helper function for creating empty files.
  4. Directory.GetFileSystemEntries is used to list directory contents.
  5. Directory.SetCurrentDirectory changes the current working directory.
  6. We use a recursive function VisitDirectory to visit all subdirectories and files.
  7. Error handling and cleanup are managed using a Try...Finally block.
  8. We use string interpolation ($"...") for formatting output strings.

To run this program:

  1. Save the code in a file with a .vb extension (e.g., DirectoryOperations.vb).

  2. Compile the code using the Visual Basic compiler:

    vbc DirectoryOperations.vb
  3. Run the compiled executable:

    DirectoryOperations.exe

This example showcases Visual Basic .NET’s approach to file system operations, demonstrating its object-oriented nature and the use of .NET Framework classes for file and directory manipulation.