test team test team - 1 month ago 8
Vb.net Question

How to copy files from desktop folder to usb via VB.net

There are 5 PCs in my shop 3 windows 7 and 2 windows XP. Every PC is operated by different users with their account (Account names are different). A main folder called "papers" (unique) is in every PC's desktop. The folder "papers" contains subfolders and files also. I want to copy that folder(papers) to my USB stick when I clicked the application from the root of the USB.

User 1 : C:\Users\Peter\Desktop\papers\
User 2 : C:\Users\Ruwan\Desktop\papers\
User 3 : C:\Users\Sam\Desktop\papers\
User 4 : C:\Users\Roshy\Desktop\papers\
User 5 : C:\Users\Veronica\Desktop\papers\

Here the user's name is change to different users.


In the coding, I assigned the value for FileToCopy as a single file (Java_OOPs.docx). I want to chage the FileToCopy value, to copy the entire "papers" folder to the USB.

My question is how to copy the folder (papers) and sub folder to the USB and a common name (Because the user's name is changing) for the desktop folder(access the desktop "papers" folder)

Note : This application may able to run on Windows XP too.

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim Gig As Long = 1073741824
Dim FileToCopy As String = "C:\Users\Peter\Desktop\papers\Java_OOPs.docx"

Try
For Each drive As System.IO.DriveInfo In System.IO.DriveInfo.GetDrives
If drive.DriveType = IO.DriveType.Removable AndAlso drive.IsReady AndAlso drive.AvailableFreeSpace >= 2 * Gig Then

Dim DriveLetter As String = drive.Name
Dim PathToUSBDrive = DriveLetter & IO.Path.GetFileName(FileToCopy)
IO.File.Copy(FileToCopy, PathToUSBDrive)

End If
Next
Catch ex As Exception
End Try

End Sub

End Class

Answer
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim Gig As Long = 1073741824L
        Dim FolderToCopy As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "papers")

        Try
            For Each Drive As IO.DriveInfo In IO.DriveInfo.GetDrives
                Select Case True
                    Case Not Drive.DriveType = IO.DriveType.Removable
                    Case Not Drive.IsReady
                    Case Not Drive.AvailableFreeSpace >= 2 * Gig
                    Case Else
                        Debug.Print("Copying {0} to {1}", FolderToCopy, Drive.RootDirectory.FullName)
                        My.Computer.FileSystem.CopyDirectory(FolderToCopy, Drive.RootDirectory.FullName, True)

                        ' Only do the copy once to first appropriate drive
                        Exit For
                End Select
            Next
        Catch ex As Exception
            Debug.Print(ex.ToString)
        End Try

    End Sub

End Class
Comments