File System Commands and Functions

 

VB.NET provides many ways to perform file system operations, such as copying files, moving files, deleting files, creating directories, obtaining a list of files within a directory, etc. In this topic, we will look at the sets of file system functionality provided by three namespace libraries:

 

The table below shows a list of commonly used functions, along with the way to accomplish that function in each of the three libraries.

 

Purpose

System.IO

My.Computer.FileSystem

Microsoft.VisualBasic

Create (make) a directory

Directory.CreateDirectory(pathname)

My.Computer.FileSystem.CreateDirectory(pathname)

MkDir(pathname)

Delete (remove) a directory

Directory.Delete(pathname)

My.Computer.FileSystem.DeleteDirectory(pathname)

RmDir(pathname)

Copy a file

File.Copy(oldfilespec, newfilespec)

My.Computer.FileSystem.CopyFile(oldfilespec, newfilespec)

FileCopy(oldfilespec,newfilespec)

Rename a file

File.Move(oldfilespec, newfilespec)

My.Computer.FileSystem.RenameFile(oldfilespec, newfilespec)

Rename(oldfilespec,newfilespec)

Delete a file

File.Delete(filespec)

My.Computer.FileSystem.DeleteFile(filespec)

Kill (filespec)

Move a file

File.Move(oldfilespec, newfilespec)…

My.Computer.FileSystem.MoveFile(oldfilespec, newfilespec)

FileCopy(oldfilespec,newfilespec)

followed by

Kill (oldfilespec)

Test for existence of a file

If File.Exists(filespec) Then …

If My.Computer.FileSystem.FileExists(filespec) Then …

If Dir(filespec) <> "" Then …

Test for existence of a directory

If Directory.Exists(path) Then …

If My.Computer.FileSystem. Directory Exists(path) Then …

If Dir(path, vbDirectory) <> "" Then …

Get list of files in a directory

Use the Directory.GetFiles method Example:

Dim astrFN() As String _

     =   Directory.GetFiles("C:\SomeDir")

For Each strFileName In astrFN

            Console.WriteLIne (strFileName)

Next

Use the GetFiles method Example:

Dim astrFN As _

         System.Collections.ObjectModel.ReadOnlyCollection(Of String)  _

      = My.Computer.FileSystem.GetFiles("C:\SomeDir")

For Each strFileName In astrFN

    Console.WriteLIne (strFileName)

Next

 

Use the Dir function. Example:

Dim strFIleName As String

strFileName = Dir("C:\SomeDir\*.*")

Do While strFileName <> ""

    Console.WriteLIne(strFileName)

    strFileName = Dir()

Loop

Get the file date/time (the last time the file was written to)

Use the File.GetLastWriteTime method Example:

Dim dtmFileDateTime As Date = _

    File.GetLastWriteTime("C:\SomeDIr\SomeFile.txt")

Console.WriteLIne(dtmFileDateTime.ToString)

Use the GetFileInfo method to get the properties of the file into a FileInfo object, then use the LastWriteTime property of the FileInfo object. Example:

Dim fi As FileInfo =  _

       My.Computer.FileSystem.GetFileInfo("C:\SomeDIr\SomeFile.txt")

Dim dtmFileDateTime As Date = fi.GetLastWriteTime

Console.WriteLIne(dtmFileDateTime.ToString)

Use the FileDateTime function. Example:

Dim dtmFileDateTime As Date = _

    FileDateTime("C:\SomeDIr\SomeFile.txt")

Console.WriteLIne(dtmFileDateTime.ToString)

Get the size of a file

Use the System.IO.GetFileInfo method to get the properties of the file into a FileInfo object, then use the Length property of the FileInfo object. Example:

Dim fi As FileInfo =  _

       System.IO.GetFileInfo("C:\SomeDIr\SomeFile.txt")

Dim lngFileLen As Long= fi.Length

Console.WriteLIne(dtmFileDateTime.ToString)

Use the GetFileInfo method to get the properties of the file into a FileInfo object, then use the Length property of the FileInfo object. Example:

Dim fi As FileInfo =  _

       My.Computer.FileSystem.GetFileInfo("C:\SomeDIr\SomeFile.txt")

Dim lngFileLen As Long= fi.Length

Console.WriteLIne(dtmFileDateTime.ToString)

Use the FileLen function. Example:

Dim lngFileLen As Long = _

    FileLen ("C:\SomeDIr\SomeFile.txt")

Console.WriteLIne(lngFileLen.ToString)

 

Sample Programs

 

As a vehicle to demonstrate commonly used file system commands and functions, the tasks in a student exercise to practice MS-DOS (Windows command line) commands has become the work to be done by the sample programs (each of the three sample programs accomplish the same exact tasks, however they will use the System.IO, My.Computer.FileSystem, and Microsoft.VisualBasic libraries respectively).

 

Let us take a look at the original student exercise. The students were given a floppy disk (now it would be a flash drive) containing the following files, all in the root directory:

 

 

The students were instructed to make six directories on their disk and move the indicated files to their proper directory as shown below. When done with this step, there should be NO files in the root directory.

 

Create a directory called:

For files with these extensions:

SYSTEM

.SYS

COMMAND

.COM

EXECUTE

.EXE

INITIAL

.INI

TEXT

.TXT

WRITE

.WRI

 

To do this step they would have to do the following:

 

First, make the directories:

 

      MD SYSTEM

      MD COMMAND

      MD EXECUTE

      MD INITIAL

      MD TEXT

      MD WRITE

 

Next, they would have to move the appropriate set of files from the root to the proper directory. This could be accomplished with either a set of MOVE commands or a set of COPY and DELETE combinations:

 

      MOVE A:\*.SYS A:\SYSTEM

      MOVE A:\*.COM A:\COMMAND

      MOVE A:\*.EXE A:\EXECUTE

      MOVE A:\*.INI A:\INITIAL

      MOVE A:\*.TXT A:\TEXT

      MOVE A:\*.WRI A:\WRITE

 

               - or -

 

      COPY A:\*.SYS A:\SYSTEM

      DEL A:\*.SYS

      COPY A:\*.COM A:\COMMAND

      DEL A:\*.COM

      COPY A:\*.EXE A:\EXECUTE

      DEL A:\*.EXE

      COPY A:\*.INI A:\INITIAL

      DEL A:\*.INI

      COPY A:\*.TXT A:\TEXT

      DEL A:\*.TXT

      COPY A:\*.WRI A:\WRITE

      DEL A:\*.WRI

 

Note: The reference to "A:" drive is appropriate for a floppy disk drive (rare these days). Today, this exercise would likely be done on a flash drive, so whatever drive letter is assigned to the flash drive would have to be used instead.

 

For the last step, they were instructed as follows:

 

Below the SYSTEM subdirectory, create a directory called EXE_INI.  Place copies of the .EXE and .INI files there. Below the INITIAL subdirectory, create a directory call TXT_WRI.  Place copies of the .TXT and .WRI files there.

 

To do this, they would have to issue the following commands:

 

      MD A:\SYSTEM\EXE_INI

      COPY A:\EXECUTE\*.EXE A:\SYSTEM\EXE_INI

      COPY A:\INITIAL\*.INI A:\SYSTEM\EXE_INI

 

      MD A:\INITIAL\TXT_WRI

      COPY A:\TEXT\*.TXT A:\INITIAL\TXT_WRI

      COPY A:\WRITE\*.INI A:\ INITIAL\TXT_WRI

 

The student would then turn their disk into the instructor, who would check to make sure that all the proper directories were created and that the files were in the right place.

 

As a follow-up exercise, students were given the disks back and asked to restore the disk back to its original state – i.e., all files back in the root with no subdirectories.

 

To do this, they would have to move the *.SYS, *.COM, *.EXE, *.INI, *.TXT, and *.WRI files from their respective top-level directories back to the root. This could be accomplished with the following MS-DOS (Windows command-line) commands:

 

      MOVE A:\SYSTEM\*.* A:\

      MOVE A:\COMMAND\*.* A:\

      MOVE A:\EXECUTE\*.* A:\

      MOVE A:\INITIAL\*.* A:\

      MOVE A:\TEXT\*.* A:\

      MOVE A:\WRITE\*.* A:\

 

At this point, the COMMAND, EXECUTE, TEXT, and WRITE subdirectories are cleared out, so they could be removed with the "remove directory" command (RMDIR or RD) as follows:

 

      RD A:\COMMAND

      RD A:\EXECUTE

      RD A:\TEXT

      RD A:\WRITE

 

However, since second-level directories were created below both the SYSTEM and the INITIAL directories, those directories must be cleared out before they can be removed (the RD command will only work if the directory to be removed is empty).

 

Therefore, the files in the EXE_INI directory below the SYSTEM directory must be deleted:

 

      DEL A:\SYSTEM\EXE_INI\*.*

 

Then the EXE_INI directory can be removed:

 

      RD A:\SYSTEM\EXE_INI

 

Then the top-level SYSTEM directory can be removed:

 

      RD A:\SYSTEM

 

A similar set of commands is necessary to clear the INITIAL directory:

 

      DEL A:\INITIAL\TXT_WRI\*.*

      RD A:\INITIAL\TXT_WRI

      RD A:\INITIAL

 

At this point, the exercise would be complete and the disk could be turned back into the instructor.

 

To do the sample project that implements these actions, you need a "clean" (empty) flash drive. The sample files shown above (the .SYS, .INI, etc.) should then be copied to that flash drive. The project downloads below, when unzipped, contain a folder called "FileSysDemoFiles", from where the files can be copied. (As an alternative, you can simply make empty files using Notepad and save them with those names, and then copy them to the flash drive. For the purpose of this exercise, the content of these files do not matter; for example, the "exe" and "com" files need not be valid executables.)

 

Prior to running the program, the contents of the flash drive should look like this:

 

 

All three versions of the program produce the same output (they write a line to the console as they complete each task). After the program creates all the necessary directories and places the files where they need to be, it pauses and suggests you look at the flash drive contents before resetting.

 

 

If you inspect the flash drive at this point, you'll see that the folders have been created and there are no files in the root. (You can also open these folders to ensure that the files are where they need to be.)

 

After you have inspected the flash drive, press Enter to do the reset:

 

 

If you look at the flash drive contents after the reset, you should see all files now back in the root, and the directories should be gone:

 

 

 

The code for the three sample programs is listed below, each program listing followed by the link to download that code. The code is heavily commented to aid in the understanding of what the code is doing.

 

Sample Program 1: Working with Files Using the System.IO Library

 

Imports System.IO

 

Module Module1

 

    Dim mstrFileDemoRoot As String = "E:"  '<-- Replace "E" with the letter of your flash drive.

    Dim mastrFiles() As String

    Dim mstrFileX As String

    Dim mobjFileInfo As FileInfo

 

    Sub Main()

 

        ' First make sure we are dealing with a removable drive (i.e. a flash drive).

        ' We don't want to be running this on a hard drive.

        'If Not DriveIsRemovable(mstrFileDemoRoot) Then

        '    Console.WriteLine("A removable drive must be used for this program.")

        '    Console.WriteLine("Press Enter to close this window.")

        '    Console.ReadLine()

        '    End

        'End If

 

        ' Make the top-level subdirectories below the file demo root with

        ' the CreateDirectory method of the System.IO Directory class ...

 

        Directory.CreateDirectory(mstrFileDemoRoot & "\SYSTEM")

        Directory.CreateDirectory(mstrFileDemoRoot & "\COMMAND")

        Directory.CreateDirectory(mstrFileDemoRoot & "\EXECUTE")

        Directory.CreateDirectory(mstrFileDemoRoot & "\INITIAL")

        Directory.CreateDirectory(mstrFileDemoRoot & "\TEXT")

        Directory.CreateDirectory(mstrFileDemoRoot & "\WRITE")

 

        Console.WriteLine("Top-level directories have been made.")

 

        ' Use the GetFiles method of the Directory class to get a list of

        ' all the files in the file demo root directory.

        ' (The list is returned as a string array, and each filename in the

        ' list will contain the full path and filename.)

 

        mastrFiles = Directory.GetFiles(mstrFileDemoRoot)

 

        ' Loop through the array of files using a For/Each loop ...

        For Each mstrFileX In mastrFiles

            ' Create a "FileInfo" object for the current file (mstrFileX) that

            ' we are processing. Using this will make it easy to extract the extension

            ' and filename portion of the current file being processed.

            mobjFileInfo = New FileInfo(mstrFileX)

            ' The Select Case structure below tests the extension of the current file

            ' and moves that file to the designated subdirectory. The moves are accomplished

            ' with the Move method of the System.IO File class ...

            Select Case mobjFileInfo.Extension.ToUpper

                Case ".SYS"

                    File.Move(mstrFileX, mstrFileDemoRoot & "\SYSTEM\" & mobjFileInfo.Name)

                Case ".COM"

                    File.Move(mstrFileX, mstrFileDemoRoot & "\COMMAND\" & mobjFileInfo.Name)

                Case ".EXE"

                    File.Move(mstrFileX, mstrFileDemoRoot & "\EXECUTE\" & mobjFileInfo.Name)

                Case ".INI"

                    File.Move(mstrFileX, mstrFileDemoRoot & "\INITIAL\" & mobjFileInfo.Name)

                Case ".TXT"

                    File.Move(mstrFileX, mstrFileDemoRoot & "\TEXT\" & mobjFileInfo.Name)

                Case ".WRI"

                    File.Move(mstrFileX, mstrFileDemoRoot & "\WRITE\" & mobjFileInfo.Name)

            End Select

        Next

 

        Console.WriteLine("Files have been moved from the root to their respective top-level directories.")

 

        ' Create the EXE_INI subdirectory below the SYSTEM subdirectory ...

        Directory.CreateDirectory(mstrFileDemoRoot & "\SYSTEM\EXE_INI")

        Console.WriteLine("Second-level directory for EXE and INI files has been made.")

 

        ' Get the list of files in the EXECUTE subdirectory and copy them over

        ' the SYSTEM\EXE_INI subdirectory. The copies are accomplished

        ' with the Copy method of the System.IO File class ...

        mastrFiles = Directory.GetFiles(mstrFileDemoRoot & "\EXECUTE")

        For Each mstrFileX In mastrFiles

            mobjFileInfo = New FileInfo(mstrFileX)

            File.Copy(mstrFileX, mstrFileDemoRoot & "\SYSTEM\EXE_INI\" & mobjFileInfo.Name)

        Next

 

        ' Get the list of files in the INITIAL subdirectory and copy them over

        ' the SYSTEM\EXE_INI subdirectory. The copies are accomplished

        ' with the Copy method of the System.IO File class ...

        mastrFiles = Directory.GetFiles(mstrFileDemoRoot & "\INITIAL")

        For Each mstrFileX In mastrFiles

            mobjFileInfo = New FileInfo(mstrFileX)

            File.Copy(mstrFileX, mstrFileDemoRoot & "\SYSTEM\EXE_INI\" & mobjFileInfo.Name)

        Next

 

        Console.WriteLine("Files have been copied to EXE_INI directory.")

 

        ' Create the TXT_WRI subdirectory below the SYSTEM subdirectory ...

        Directory.CreateDirectory(mstrFileDemoRoot & "\INITIAL\TXT_WRI")

        Console.WriteLine("Second-level directory for TXT and WRI files has been made.")

        ' Get the list of files in the TEXT subdirectory and copy them over

        ' the INITIAL\TXT_WRI subdirectory. The copies are accomplished

        ' with the Copy method of the System.IO File class ...

        mastrFiles = Directory.GetFiles(mstrFileDemoRoot & "\TEXT")

        For Each mstrFileX In mastrFiles

            mobjFileInfo = New FileInfo(mstrFileX)

            File.Copy(mstrFileX, mstrFileDemoRoot & "\INITIAL\TXT_WRI\" & mobjFileInfo.Name)

        Next

        ' Get the list of files in the WRITE subdirectory and copy them over

        ' the INITIAL\TXT_WRI subdirectory. The copies are accomplished

        ' with the Copy method of the System.IO File class ...

        mastrFiles = Directory.GetFiles(mstrFileDemoRoot & "\WRITE")

        For Each mstrFileX In mastrFiles

            mobjFileInfo = New FileInfo(mstrFileX)

            File.Copy(mstrFileX, mstrFileDemoRoot & "\INITIAL\TXT_WRI\" & mobjFileInfo.Name)

        Next

        Console.WriteLine("Files have been copied to TXT_WRI directory.")

 

        ' The first part of the exercise is complete. You may want to inspect the contents

        ' of the file demo root directory before pressing Enter to reset.

        Console.WriteLine("")

        Console.WriteLine("The first part of the exercise is complete.")

        Console.WriteLine("You may wish to inspect the file demo directory")

        Console.WriteLine("to see the results before resetting.")

        Console.WriteLine("Press Enter to reset.")

        Console.ReadLine()

        Console.WriteLine("")

 

        ' The following group of statements cause the file demo root directory to return

        ' to its original state - all files are moved back to the root, and the individual

        ' subdirectories are deleted. This is done in a Sub called "MoveFilesBackToRoot",

        ' which is called for each of the subdirectories:

        MoveFilesBackToRoot("SYSTEM")

        MoveFilesBackToRoot("COMMAND")

        MoveFilesBackToRoot("EXECUTE")

        MoveFilesBackToRoot("INITIAL")

        MoveFilesBackToRoot("TEXT")

        MoveFilesBackToRoot("WRITE")

 

        Console.WriteLine("")

        Console.WriteLine("The second part of the exercise is complete.")

        Console.WriteLine("Press Enter to close this window.")

        Console.ReadLine()

 

    End Sub

 

    Private Sub MoveFilesBackToRoot(ByVal pstrDirectory As String)

 

        ' Use the GetFiles method of the Directory class to get a list of

        ' all the files in the passed-in subdirectory of the file demo root directory.

        mastrFiles = Directory.GetFiles(mstrFileDemoRoot & "\" & pstrDirectory)

 

        ' Move each file in the specified subdirectory back to the file demo root.

        For Each mstrFileX In mastrFiles

            mobjFileInfo = New FileInfo(mstrFileX)

            File.Move(mstrFileX, mstrFileDemoRoot & "\" & mobjFileInfo.Name)

        Next

 

        ' Delete the individual subdirectory.

        Directory.Delete(mstrFileDemoRoot & "\" & pstrDirectory, True)

 

        Console.WriteLine(pstrDirectory & " directory has been cleared; files moved back to root.")

 

    End Sub

 

    ' Helper function below to ensure a removable drive is being used

    Private Function DriveIsRemovable(ByVal pstrDriveLetter As String) As Boolean

 

        Dim allDrives() As DriveInfo = DriveInfo.GetDrives()

        Dim d As DriveInfo

        For Each d In allDrives

            If d.DriveType = DriveType.Removable And d.Name.ToUpper.StartsWith(pstrDriveLetter.ToUpper) Then

                Return True

            End If

        Next

 

        Return False

 

    End Function

 

End Module

 

Download the VB project code for the example above here.

 

 

Sample Program 2: Working with Files Using the My.Computer.FileSystem Library

 

Module Module1

 

    Dim mstrFileDemoRoot As String = "E:"  '<-- Replace "E" with the letter of your flash drive.

    Dim mastrFiles As Collections.ObjectModel.ReadOnlyCollection(Of String)

    Dim mstrFileX As String

    Dim mobjFileInfo As System.IO.FileInfo

 

    Sub Main()

 

        ' First make sure we are dealing with a removable drive (i.e. a flash drive).

        ' We don't want to be running this on a hard drive.

        If Not DriveIsRemovable(mstrFileDemoRoot) Then

            Console.WriteLine("A removable drive must be used for this program.")

            Console.WriteLine("Press Enter to close this window.")

            Console.ReadLine()

            End

        End If

 

        With My.Computer.FileSystem

 

            ' Make the top-level subdirectories below the file demo root with

            ' the CreateDirectory method of the System.IO Directory class ...

 

            .CreateDirectory(mstrFileDemoRoot & "\SYSTEM")

            .CreateDirectory(mstrFileDemoRoot & "\COMMAND")

            .CreateDirectory(mstrFileDemoRoot & "\EXECUTE")

            .CreateDirectory(mstrFileDemoRoot & "\INITIAL")

            .CreateDirectory(mstrFileDemoRoot & "\TEXT")

            .CreateDirectory(mstrFileDemoRoot & "\WRITE")

 

            Console.WriteLine("Top-level directories have been made.")

 

            ' Use the GetFiles method of the My.Computer.FileSystem class to get a list of

            ' all the files in the file demo root. (The list is returned as a read-only

            ' collection of strings, and each filename in the collection will contain the

            ' full path and filename.)

 

            mastrFiles = .GetFiles(mstrFileDemoRoot)

 

            ' Loop through the collection of files using a For/Each loop ...

            For Each mstrFileX In mastrFiles

                ' Create a "FileInfo" object for the current file (mstrFileX) that

                ' we are processing. Using this will make it easy to extract the extension

                ' and filename portion of the current file being processed.

                mobjFileInfo = .GetFileInfo(mstrFileX)

                ' The Select Case structure below tests the extension of the current file

                ' and moves that file to the designated sub. The moves are accomplished

                ' with the MoveFile method of the My.Computer.FileSystem File class ...

                Select Case mobjFileInfo.Extension.ToUpper

                    Case ".SYS"

                        .MoveFile(mstrFileX, mstrFileDemoRoot & "\SYSTEM\" & mobjFileInfo.Name)

                    Case ".COM"

                        .MoveFile(mstrFileX, mstrFileDemoRoot & "\COMMAND\" & mobjFileInfo.Name)

                    Case ".EXE"

                        .MoveFile(mstrFileX, mstrFileDemoRoot & "\EXECUTE\" & mobjFileInfo.Name)

                    Case ".INI"

                        .MoveFile(mstrFileX, mstrFileDemoRoot & "\INITIAL\" & mobjFileInfo.Name)

                    Case ".TXT"

                        .MoveFile(mstrFileX, mstrFileDemoRoot & "\TEXT\" & mobjFileInfo.Name)

                    Case ".WRI"

                        .MoveFile(mstrFileX, mstrFileDemoRoot & "\WRITE\" & mobjFileInfo.Name)

                End Select

            Next

 

            Console.WriteLine("Files have been moved from the root to their respective top-level directories.")

 

            ' Create the EXE_INI subdirectory below the SYSTEM subdirectory ...

            .CreateDirectory(mstrFileDemoRoot & "\SYSTEM\EXE_INI")

            Console.WriteLine("Second-level directory for EXE and INI files has been made.")

            ' Get the list of files in the EXECUTE subdirectory and copy them over

            ' the SYSTEM\EXE_INI sub. The copies are accomplished with the CopyFile method

            ' of the My.Computer.FileSystem File class ...

            mastrFiles = .GetFiles(mstrFileDemoRoot & "\EXECUTE")

            For Each mstrFileX In mastrFiles

                mobjFileInfo = .GetFileInfo(mstrFileX)

                .CopyFile(mstrFileX, mstrFileDemoRoot & "\SYSTEM\EXE_INI\" & mobjFileInfo.Name)

            Next

            ' Get the list of files in the INITIAL subdirectory and copy them over

            ' the SYSTEM\EXE_INI sub. The copies are accomplished with the CopyFile method

            ' of the My.Computer.FileSystem File class ...

            mastrFiles = .GetFiles(mstrFileDemoRoot & "\INITIAL")

            For Each mstrFileX In mastrFiles

                mobjFileInfo = .GetFileInfo(mstrFileX)

                .CopyFile(mstrFileX, mstrFileDemoRoot & "\SYSTEM\EXE_INI\" & mobjFileInfo.Name)

            Next

            Console.WriteLine("Files have been copied to EXE_INI .")

 

            ' Create the TXT_WRI subdirectory below the SYSTEM subdirectory ...

            .CreateDirectory(mstrFileDemoRoot & "\INITIAL\TXT_WRI")

            Console.WriteLine("Second-level directory for TXT and WRI files has been made.")

            ' Get the list of files in the TEXT subdirectory and copy them over

            ' the INITIAL\TXT_WRI sub. The copies are accomplished with the CopyFile method

            ' of the My.Computer.FileSystem File class ...

            mastrFiles = .GetFiles(mstrFileDemoRoot & "\TEXT")

            For Each mstrFileX In mastrFiles

                mobjFileInfo = New System.IO.FileInfo(mstrFileX)

                .CopyFile(mstrFileX, mstrFileDemoRoot & "\INITIAL\TXT_WRI\" & mobjFileInfo.Name)

            Next

            ' Get the list of files in the WRITE subdirectory and copy them over

            ' the INITIAL\TXT_WRI sub. The copies are accomplished with the CopyFile method

            ' of the My.Computer.FileSystem File class ...

            mastrFiles = .GetFiles(mstrFileDemoRoot & "\WRITE")

            For Each mstrFileX In mastrFiles

                mobjFileInfo = New System.IO.FileInfo(mstrFileX)

                .CopyFile(mstrFileX, mstrFileDemoRoot & "\INITIAL\TXT_WRI\" & mobjFileInfo.Name)

            Next

            Console.WriteLine("Files have been copied to TXT_WRI .")

 

        End With

 

        ' The first part of the exercise is complete. You may want to inspect the contents

        ' of the file demo root directory before pressing Enter to reset.

        Console.WriteLine("")

        Console.WriteLine("The first part of the exercise is complete.")

        Console.WriteLine("You may wish to inspect the file demo directory")

        Console.WriteLine("to see the results before resetting.")

        Console.WriteLine("Press Enter to reset.")

        Console.ReadLine()

        Console.WriteLine("")

 

        ' The following group of statements cause the file demo root directory to return

        ' to its original state - all files are moved back to the root, and the individual

        ' subdirectories are deleted. This is done in a Sub called "MoveFilesBackToRoot",

        ' which is called for each of the subdirectories:

        MoveFilesBackToRoot("SYSTEM")

        MoveFilesBackToRoot("COMMAND")

        MoveFilesBackToRoot("EXECUTE")

        MoveFilesBackToRoot("INITIAL")

        MoveFilesBackToRoot("TEXT")

        MoveFilesBackToRoot("WRITE")

 

        Console.WriteLine("")

        Console.WriteLine("The second part of the exercise is complete.")

        Console.WriteLine("Press Enter to close this window.")

        Console.ReadLine()

 

    End Sub

 

    Private Sub MoveFilesBackToRoot(ByVal pstrDirectory As String)

 

        With My.Computer.FileSystem

 

            ' Use the GetFiles method of the My.Computer.FileSystem class to get a list of

            ' all the files in the passed-in subdirectory of the file demo root directory.

            mastrFiles = .GetFiles(mstrFileDemoRoot & "\" & pstrDirectory)

 

            ' Move each file in the specified subdirectory back to the file demo root.

            For Each mstrFileX In mastrFiles

                mobjFileInfo = New System.IO.FileInfo(mstrFileX)

                .MoveFile(mstrFileX, mstrFileDemoRoot & "\" & mobjFileInfo.Name)

            Next

 

            ' Delete the individual subdirectory.

            .DeleteDirectory(mstrFileDemoRoot & "\" & pstrDirectory, _

                             FileIO.DeleteDirectoryOption.DeleteAllContents)

 

            Console.WriteLine(pstrDirectory & " directory has been cleared; files moved back to root.")

 

        End With

 

    End Sub

 

    ' Helper function below to ensure a removable drive is being used

    Private Function DriveIsRemovable(ByVal pstrDriveLetter As String) As Boolean

 

        Dim allDrives() As DriveInfo = DriveInfo.GetDrives()

        Dim d As DriveInfo

        For Each d In allDrives

            If d.DriveType = DriveType.Removable And d.Name.ToUpper.StartsWith(pstrDriveLetter.ToUpper) Then

                Return True

            End If

        Next

 

        Return False

 

    End Function

 

End Module

 

Download the VB project code for the example above here.

 

Sample Program 3: Working with Files Using the Microsoft.VisualBasic Library

 

Module Module1

 

    Dim mstrFileDemoRoot As String = "E:"   '<-- Replace "E" with the letter of your flash drive.

    Dim mstrFileX As String

 

    Sub Main()

 

        ' First make sure we are dealing with a removable drive (i.e. a flash drive).

        ' We don't want to be running this on a hard drive.

        If Not DriveIsRemovable(mstrFileDemoRoot) Then

            Console.WriteLine("A removable drive must be used for this program.")

            Console.WriteLine("Press Enter to close this window.")

            Console.ReadLine()

            End

        End If

 

        ' Make the top-level subdirectories below the file demo root with the MkDir statement ...

 

        MkDir(mstrFileDemoRoot & "\SYSTEM")

        MkDir(mstrFileDemoRoot & "\COMMAND")

        MkDir(mstrFileDemoRoot & "\EXECUTE")

        MkDir(mstrFileDemoRoot & "\INITIAL")

        MkDir(mstrFileDemoRoot & "\TEXT")

        MkDir(mstrFileDemoRoot & "\WRITE")

 

        Console.WriteLine("Top-level directories have been made.")

 

        ' Use the Dir function to get a list of all the files in the file demo root.

        ' The Dir function can then be used repeatedly in a loop to return each file

        ' one-by-one.

 

        mstrFileX = Dir(mstrFileDemoRoot & "\*.*")

 

        ' Loop through the collection of files using a For/Each loop ...

        Do Until mstrFileX = ""

            ' The Select Case structure below tests the extension of the current file

            ' and moves that file to the designated subdirectory. The moves are actually

            ' accomplished by using a combination of the FileCopy statement and Kill statement.

            Select Case Strings.Right(mstrFileX, 4).ToUpper

                Case ".SYS"

                    FileCopy(mstrFileDemoRoot & "\" & mstrFileX, _

                             mstrFileDemoRoot & "\SYSTEM\" & mstrFileX)

                    Kill(mstrFileDemoRoot & "\" & mstrFileX)

                Case ".COM"

                    FileCopy(mstrFileDemoRoot & "\" & mstrFileX, _

                             mstrFileDemoRoot & "\COMMAND\" & mstrFileX)

                    Kill(mstrFileDemoRoot & "\" & mstrFileX)

                Case ".EXE"

                    FileCopy(mstrFileDemoRoot & "\" & mstrFileX, _

                             mstrFileDemoRoot & "\EXECUTE\" & mstrFileX)

                    Kill(mstrFileDemoRoot & "\" & mstrFileX)

                Case ".INI"

                    FileCopy(mstrFileDemoRoot & "\" & mstrFileX, _

                             mstrFileDemoRoot & "\INITIAL\" & mstrFileX)

                    Kill(mstrFileDemoRoot & "\" & mstrFileX)

                Case ".TXT"

                    FileCopy(mstrFileDemoRoot & "\" & mstrFileX, _

                             mstrFileDemoRoot & "\TEXT\" & mstrFileX)

                    Kill(mstrFileDemoRoot & "\" & mstrFileX)

                Case ".WRI"

                    FileCopy(mstrFileDemoRoot & "\" & mstrFileX, _

                             mstrFileDemoRoot & "\WRITE\" & mstrFileX)

                    Kill(mstrFileDemoRoot & "\" & mstrFileX)

            End Select

            mstrFileX = Dir()

        Loop

 

        Console.WriteLine("Files have been moved from the root to their respective top-level directories.")

 

        ' Create the EXE_INI subdirectory below the SYSTEM subdirectory ...

        MkDir(mstrFileDemoRoot & "\SYSTEM\EXE_INI")

        Console.WriteLine("Second-level directory for EXE and INI files has been made.")

        ' Get the list of files in the EXECUTE subdirectory and copy them over

        ' the SYSTEM\EXE_INI sub. The copies are accomplished with the FileCopy statement.

        mstrFileX = Dir(mstrFileDemoRoot & "\EXECUTE\*.*")

        Do Until mstrFileX = ""

            FileCopy(mstrFileDemoRoot & "\EXECUTE\" & mstrFileX, _

                     mstrFileDemoRoot & "\SYSTEM\EXE_INI\" & mstrFileX)

            mstrFileX = Dir()

        Loop

        ' Get the list of files in the INITIAL subdirectory and copy them over

        ' the SYSTEM\EXE_INI sub. The copies are accomplished with the FileCopy statement.

        mstrFileX = Dir(mstrFileDemoRoot & "\INITIAL\*.*")

        Do Until mstrFileX = ""

            FileCopy(mstrFileDemoRoot & "\INITIAL\" & mstrFileX, _

                     mstrFileDemoRoot & "\SYSTEM\EXE_INI\" & mstrFileX)

            mstrFileX = Dir()

        Loop

        Console.WriteLine("Files have been copied to EXE_INI.")

 

        ' Create the TXT_WRI subdirectory below the SYSTEM subdirectory ...

        MkDir(mstrFileDemoRoot & "\INITIAL\TXT_WRI")

        Console.WriteLine("Second-level directory for TXT and WRI files has been made.")

        ' Get the list of files in the TEXT subdirectory and copy them over

        ' the INITIAL\TXT_WRI sub. The copies are accomplished with the FileCopy statement.

        mstrFileX = Dir(mstrFileDemoRoot & "\TEXT")

        Do Until mstrFileX = ""

            FileCopy(mstrFileDemoRoot & "\TEXT\" & mstrFileX, _

                     mstrFileDemoRoot & "\INITIAL\TXT_WRI\" & mstrFileX)

            mstrFileX = Dir()

        Loop

        ' Get the list of files in the WRITE subdirectory and copy them over

        ' the INITIAL\TXT_WRI sub. The copies are accomplished with the FileCopy statement.

        mstrFileX = Dir(mstrFileDemoRoot & "\WRITE\*.*")

        Do Until mstrFileX = ""

            FileCopy(mstrFileDemoRoot & "\WRITE\" & mstrFileX, _

                     mstrFileDemoRoot & "\INITIAL\TXT_WRI\" & mstrFileX)

            mstrFileX = Dir()

        Loop

        Console.WriteLine("Files have been copied to TXT_WRI.")

 

        ' The first part of the exercise is complete. You may want to inspect the contents

        ' of the file demo root directory before pressing Enter to reset.

        Console.WriteLine("")

        Console.WriteLine("The first part of the exercise is complete.")

        Console.WriteLine("You may wish to inspect the file demo directory")

        Console.WriteLine("to see the results before resetting.")

        Console.WriteLine("Press Enter to reset.")

        Console.ReadLine()

        Console.WriteLine("")

 

        ' The following group of statements cause the file demo root directory to return

        ' to its original state - all files are moved back to the root, and the individual

        ' subdirectories are deleted. This is done in a Sub called "MoveFilesBackToRoot",

        ' which is called for each of the subdirectories:

        MoveFilesBackToRoot("SYSTEM")

        MoveFilesBackToRoot("COMMAND")

        MoveFilesBackToRoot("EXECUTE")

        MoveFilesBackToRoot("INITIAL")

        MoveFilesBackToRoot("TEXT")

        MoveFilesBackToRoot("WRITE")

 

        Console.WriteLine("")

        Console.WriteLine("The second part of the exercise is complete.")

        Console.WriteLine("Press Enter to close this window.")

        Console.ReadLine()

 

    End Sub

 

    Private Sub MoveFilesBackToRoot(ByVal pstrDirectory As String)

 

        mstrFileX = Dir(mstrFileDemoRoot & "\" & pstrDirectory & "\*.*")

        Do Until mstrFileX = ""

            FileCopy(mstrFileDemoRoot & "\" & pstrDirectory & "\" & mstrFileX, _

                     mstrFileDemoRoot & "\" & mstrFileX)

            Kill(mstrFileDemoRoot & "\" & pstrDirectory & "\" & mstrFileX)

            mstrFileX = Dir()

        Loop

 

        If pstrDirectory = "SYSTEM" Then

            Kill(mstrFileDemoRoot & "\SYSTEM\EXE_INI\*.*")

            ' "sleep" for 2 seconds to make sure files are really gone before removing directory

            Threading.Thread.Sleep(2000)

            RmDir(mstrFileDemoRoot & "\SYSTEM\EXE_INI")

        ElseIf pstrDirectory = "INITIAL" Then

            Kill(mstrFileDemoRoot & "\INITIAL\TXT_WRI\*.*")

            ' "sleep" for 2 seconds to make sure files are really gone before removing directory

            Threading.Thread.Sleep(2000)

            RmDir(mstrFileDemoRoot & "\INITIAL\TXT_WRI")

        End If

 

        RmDir(mstrFileDemoRoot & "\" & pstrDirectory)

 

        Console.WriteLine(pstrDirectory & " directory has been cleared; files moved back to root.")

 

    End Sub

 

 

    ' Helper function below to ensure a removable drive is being used

    Private Function DriveIsRemovable(ByVal pstrDriveLetter As String) As Boolean

 

        Dim allDrives() As System.IO.DriveInfo = System.IO.DriveInfo.GetDrives()

        Dim d As System.IO.DriveInfo

        For Each d In allDrives

            If d.DriveType = System.IO.DriveType.Removable And d.Name.ToUpper.StartsWith(pstrDriveLetter.ToUpper) Then

                Return True

            End If

        Next

 

        Return False

 

    End Function

 

End Module

 

Download the VB project code for the example above here.