Link to home
Create AccountLog in
Avatar of josephh610
josephh610

asked on

In vb.net how do I copy files listed in my listbox to the file system

In vb.net how do I copy files listed in my listbox to the file system
I used a fileopen box to populate my list box and now when I click a button I want to copy those from the place they reside on the file system to another place?
Avatar of Jeff Certain
Jeff Certain
Flag of United States of America image

The code below will loop through the files in your list, assuming you've put them in a listbox called lbFiles.

Right now, it moves them to C:\Temp.
		Dim destinationRoot As String = "C:\Temp"
		For Each fileName As String In lbFiles.Items
			Dim index As Integer = fileName.LastIndexOf("\")
			Dim newFileName As String = destinationRoot & fileName.Substring(index)
			If System.IO.File.Exists(fileName) Then System.IO.File.Move(fileName, newFileName)
		Next

Open in new window

Avatar of josephh610
josephh610

ASKER

All I did was change the name of the list box to MainForm.ListBox1.Items and try to run it and I get this error:

System.ArgumentOutOfRangeException was unhandled
  Message="StartIndex cannot be less than zero.
Parameter name: startIndex"
  ParamName="startIndex"
  Source="mscorlib"
 
ASKER CERTIFIED SOLUTION
Avatar of Jeff Certain
Jeff Certain
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Well my problem is I populated the list box with a openfile dialog and it possible that some files have a differnt source dir. Here's my code to collect.

Public Sub PopulateListBox()
 
        MainForm.OpenFileDialog1.ShowDialog()
 
        ' Make sure the User selected one or more files
        If (MainForm.OpenFileDialog1.FileNames.Length > 0) Then
            ' Loop through the list of selected filenames and add each one to your listbox
            For Each strFileName As String In MainForm.OpenFileDialog1.FileNames
                MainForm.ListBox1.Items.Add(Path.GetFileName(strFileName))
            Next
        End If
    End Sub

Open in new window