Tuesday, August 4, 2015

Directories VB.net



Hey guys. Today I will do a very simple tutorial to explain how to create and delete directories. So, let´s go! Maybe this is a stupid tutorial but is just for you understand the basic code of creating folders and subfolders, and also how to delete it.
First open your Visual Studio and Create a New Project using Visual Basic. Rename it if you want.
Add two textbox and two buttons. The first button, rename it as “Create” and the second one as “Delete”.

Create Directory

Double-Click in the button named as “Create”
Private Sub Button1_Click(sender AsSystem.Object, e AsSystem.EventArgs) HandlesButton1.Click
        Try
            System.IO.Directory.CreateDirectory(TextBox1.Text)
        Catchex As Exception
            MsgBox(ex.Message, vbCritical + vbOKOnly, "Error")
        End Try
    End Sub

Delete Directory

Double-Click in the button named as “Delete”
Private Sub Button2_Click(sender AsSystem.Object, e AsSystem.EventArgs) HandlesButton2.Click
        Try
            System.IO.Directory.Delete(TextBox2.Text)
        Catchex As Exception
            MsgBox(ex.Message, vbCritical + vbOKOnly, "Error")
        EndTry
    EndSub


Check if a directory exists

But to prevent errors here you first you should check if the directory exists like in next example:
Private Sub Button2_Click(sender AsSystem.Object, e AsSystem.EventArgs) HandlesButton2.Click
        IfSystem.IO.Directory.Exists(TextBox2.Text) Then
            Try
                System.IO.Directory.Delete(TextBox2.Text)
            Catch ex As Exception
                MsgBox(ex.Message, vbCritical + vbOKOnly, "Error")
            End Try
        EndIf
    EndSub

No comments:

Post a Comment