Add/Removing Directories

By KuTsuM on Sep 26, 2007

This snippet will show you how to add and remove directories, as well as check if they exist already or not in VB.NET.

Module DirInfo
    Sub Main()
        ' Declare the directory that you want to create.
        Dim dir As DirectoryInfo = New DirectoryInfo("c:\MyDir")
        Try
            ' Determine whether the folder exists.
            If dir.Exists Then
                ' Outputs to the console to tell the user if it exists already
                System.Console.WriteLine("That path exists already.")
                Return
            End If

            ' Attempt to create the folder.
            dir.Create()
            System.Console.WriteLine("The directory was created successfully.")
            System.Console.Writeline("Check your C:\ drive to see if the directory MyDir was added. When ready to continue, press enter..")
            System.Console.Readline()
            ' Delete the folder.
            dir.Delete()
            System.Console.WriteLine("The directory was deleted successfully.")

        Catch e As Exception
            ' If there is an error, this will catch it and output the error to the console
            System.Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
        System.Console.ReadLine()
    End Sub
End Module

Comments

Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.