Copying multiple sources to single destination - vb.net

I am new to VB.net and am trying to create a backup utility to copy a set of local folders to a single backup destination (on usb for example) with a progress bar. After googling for the last few hours I can only find examples of single folder to single destination.
Can anyone point me in the direction of an example?
UPDATE:
Based of #Werdna example, I have created a simple FOR EACH NEXT loop. However the next issue is that only the files within the source directories are being copied to the target directory, rather than the folders and all their contents. Can anyone see where I am going wrong?
Public Class Form1
Private Sub Start_Click(sender As Object, e As EventArgs) Handles Start.Click
Dim destination = "E:\Backup Folder"
Dim sources As New List(Of String)
sources.Add("D:\Profiles\Users\Desktop")
sources.Add("D:\Profiles\Users\Mail")
sources.Add("D:\Profiles\Users\Downloads")
For Each source As String In sources
My.Computer.FileSystem.CopyDirectory(source, destination)
Next
MessageBox.Show("Copy Completed")
End Sub
End Class
Also, what is the best method to use the FOR EACH NEXT loop to count the number of files to be copied? I would like to output the amount to a label as well as use it for a progressbar as the utility evolves.

here is something that i have quickly written up for you to give you some idea on how i went about completing your task. You will need to add 2 listboxes to your application, a folder open dialog and a few buttons, this might not be what you are looking for, unfortunately you cant select multiable folders with the other dialogs, however nevertheless, take a look below, the code isn't completely as there is always something to do, however this should lead you in the right direction hopefully!
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each item In IO.Directory.GetDirectories("C:\")
ListBox1.Items.Add(item)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each item In ListBox1.SelectedItems
ListBox2.Items.Add(item & "\")
Next
ListBox1.SelectedItem = Nothing
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ListBox2.Items.Remove(ListBox2.SelectedItem)
ListBox2.SelectedItem = Nothing
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each item In IO.Directory.GetDirectories(ListBox1.SelectedItem)
ListBox1.Items.Clear()
ListBox1.Items.Add(item)
Next
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If FolderBrowserDialog1.ShowDialog = DialogResult.OK Then
My.Computer.FileSystem.CreateDirectory(FolderBrowserDialog1.SelectedPath)
For Each item In ListBox2.Items
My.Computer.FileSystem.CopyDirectory(item, FolderBrowserDialog1.SelectedPath)
Next
MessageBox.Show("Copy Completed.")
End If
End Sub
End Class
I wrote this in about 10 minutes, so i didnt get a change to do a progessbar, however if this is what you are looking for, then i am happy to help you add one to your program. Happy Coding!
UPDATE - BASED OFF YOUR NEW QUESTION
Public Class Form1
Dim NumberofFILEs As Integer = 0
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim Location1 = "C:\Backup Folder\TESTING\FOLDER"
Dim source As String = "C:\TESTING\FOLDER"
Dim source1 As String = "C:\TESTING1\FOLDER"
Dim Location2 = "C:\Backup Folder\TESTING1\FOLDER"
IO.Directory.CreateDirectory("C:\Backup Folder\TESTING\FOLDER")
IO.Directory.CreateDirectory("C:\Backup Folder\TESTING1\FOLDER")
For Each item In source
My.Computer.FileSystem.CopyDirectory(source, Location1, True)
Next
For Each item In source1
My.Computer.FileSystem.CopyDirectory(source1, Location2, True)
Next
MessageBox.Show("Completed")
For Each file In source1.Count & source.Count
NumberofFILEs += 1
Next
Label1.Text = NumberofFILEs
End Sub
End Class
Edit the locations and destinations to what you need. Also the True at the end of the copydirectory means that it will overwrite any files with the same name, eg it will update them pretty much

You can copy each folder to the destination, one at a time. Loop through the source folders and copy each one to the target folder.

Related

Drag and Drop not working on shortcut or exefile

Drag&Drop is working correctly when application is running. But when a file is dropped on application shortcut or exe.file, no drag&drop event is triggered just aaplication starts.
I created simple application in Visual Studio 2019, only Form1 with following adjustments
Form1.AllowDrop = True
Private Sub Form1_DragEnter(sender As Object, e As DragEventArgs) Handles MyBase.DragEnter
If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
Private Sub Form1_DragDrop(sender As Object, e As DragEventArgs) Handles MyBase.DragDrop
Dim files() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())
Me.Text = files(0)
End Sub
Can you help me how to open my application with correct filename which is dropped on application icon/shortcut?
Thanks, Martin
Your code only handles the drag and drop on the form itself (which can be done with any other control with AllowDrop = True). Dropping a file onto the application executable file (or shortcut) is a totally different thing; what it does is simply open the application normally but with a command-line argument passed to it (i.e., the file/folder path).
To retrieve that file/folder path, you can use Environment.GetCommandLineArgs, to read the command-line arguments, make sure it returns at least two elements (the first one is your application's executable path), and then display the second (or second to last) elements.
This should work:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim args = Environment.GetCommandLineArgs()
If args.Length > 1 Then Me.Text = args(1)
End Sub
If you drop multiple files onto your program's icon and you want to display them all, you can adjust the above code to something like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim args = Environment.GetCommandLineArgs()
For Each arg In args.Skip(1)
' Do something with `arg`.
Next
End Sub

when the text in a textbox is equal to a certain word i need to value in the combo box to be saved for that text

I have orders in text files in the debug folder and when i type the name of the order in a text box it displays the order is a list box and there is a combo box underneath where i can change the status of the meal preparation (Being prepared, ready to deliver etc,). If i go back to that form and type in the same order name into the textbox i need to previous prepartion status to be already in the textbox. Thanks for any help!
Public Class frmOrderStatus
Private Sub btnStatus_Click(sender As Object, e As EventArgs) Handles btnStatus.Click
Dim sr As IO.StreamReader = IO.File.OpenText(strTxtOrderNum & ".txt")
Do Until sr.EndOfStream
lstOrder.Items.Add(sr.ReadLine)
Loop
End Sub
Private Sub OrderStatus_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstOrder.Items.Clear()
btnStatus.Enabled = False
ChangeStatus.Enabled = False
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
strTxtOrderNum = txtOrderNum2.Text
btnStatus.Enabled = True
ChangeStatus.Enabled = True
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
strSaveStatus = ChangeStatus.SelectedIndex
End Sub
Private Sub ChangeStatus_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ChangeStatus.SelectedIndexChanged
End Sub
End Class
It recognizes the file; it just tells you it is in use. A Stream must be closed and disposed. I don't see the StreamReader even being closed let alone disposed. A `Using...End Using block will close and dispose of objects even if there is an error.
I just used a text file I happened to have to test.
Private strTxtOrderNum As String = "host"
Private Sub ReadFile()
Using sr As IO.StreamReader = IO.File.OpenText(strTxtOrderNum & ".txt")
Do Until sr.EndOfStream
ListBox1.Items.Add(sr.ReadLine)
Loop
End Using
End Sub
Private Sub WriteFile()
Dim strSelectedItem = ComboBox1.Text
Using swVar As IO.StreamWriter = IO.File.AppendText(strTxtOrderNum & ".txt")
swVar.WriteLine(strSelectedItem)
End Using
End Sub

How to do you make a ListBox display all files in a drive?

I'm coding an Anti-Virus at the moment, so it's been very complicated to code it and design it. Anyway, the other day I ran into a problem, where my ListBox is not displaying all the files that are in the selected drive/directory.
I'll put some code and images so you get the idea.
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
ListBox1.Items.Clear()
ListBox3.Items.Clear()
FolderBrowserDialog1.SelectedPath = Path.GetPathRoot(Environment.SystemDirectory) & "Boot\"
On Error Resume Next
For Each strDir As String In System.IO.Directory.GetDirectories(FolderBrowserDialog1.SelectedPath)
For Each strFile As String In System.IO.Directory.GetFiles(strDir)
ListBox1.Items.Add(strFile)
ListBox3.Items.Add(strFile)
Next
Next
Timer1.Start()
End Sub
However, instead of the files appearing in the ListBox (ListBox3), it just gives a black screen. Maybe I should remove the TabControl that it is surrounded by?
See how it's black? It even happens when I run it.
Hope this helps! Comment if you need more information.
You may want to simplify your events by creating subs and standardizing the code instead of embedding it directly into the button click. I have created a working example of how to load directories and files dynamically.
I would also recommend doing a isolated experiment, you can easily throw together a test project to isolate the directories in question and the layout you are trying to achieve. It could be that there are other events causing noise in your debugging.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
load_dirs(ListBox2, "H:\")
End Sub
Sub load_files(LB As ListBox,
IO_dir As String)
Dim Files_ = IO.Directory.GetFiles(IO_dir)
With LB.Items
.Clear()
.AddRange(Files_)
End With
End Sub
Sub load_dirs(LB As ListBox,
IO_dir As String)
Dim dir_ = IO.Directory.GetDirectories(IO_dir)
With LB.Items
.Clear()
.AddRange(dir_)
End With
End Sub
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
Try
Dim lb As ListBox = sender
load_files(ListBox1, lb.SelectedItem)
Catch ex As Exception
End Try
End Sub
End Class

The form just freeze looping throught lines

I'm just stuck into something in which I can't solve it in any way. My UI freeze even with BackgroundWorker.
Regarding to my old solved problem: VB.NET - It keep replacing itself
'I have in a text file lines of this format:
word1|word2|word3
anotherword1|anotherword2
I'm trying to split each word one by one per every line of that file and once program detect if the richtextbox has one of these words will replace that word with the unsplitted line. Example: From word1 to word1|word2|word3'
Everything works great, but only if I'm using a file with a small set of lines to split. But I need to split a big one at once.
Here is what I have so far: http://pastebin.com/raw/k0MtPHbZ
As I said, everything works if I reduce the lines of the en.txt file and I'm kinda confused why. I would really appreciate if someone would tell me how to fix this problem.
UPDATE:
As you guys said look what I did:
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim list As New List(Of String)()
Using reader As New StreamReader(Application.StartupPath & "\en.txt")
Dim line As String = Nothing
Dim input = RichTextBox1.Text
While (InlineAssignHelper(line, reader.ReadLine())) IsNot Nothing
Dim pat = String.Format("\b({0})\b", line)
input = Regex.Replace(input, pat, line)
End While
RichTextBox2.Text = input
End Using
End Sub
But it still does the same. Work fine with small amount of lines. Freeze with my 500kb text file.
I believe your background worker is still going to block on your UI thread because you're referencing UI controls in the DoWork portion. You would be better off pulling in the data on the UI thread, assigning it to a variable, and then processing that all in memory in the DoWork instead of attempting to manipulate UI from a background thread, this is going to give you grief consistently.
So in your button1.Click handler, get the input from the textbox and assign it to an instance variable. Reference that instance variable inside your DoWork for the input.
Example:
Public Class Form1
Private _textInput As String = String.Empty
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
_textInput = RichTextBOx1.Text
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For i = 0 To 100
Threading.Thread.Sleep(200)
Dim list As New List(Of String)()
Using reader As New StreamReader(Application.StartupPath & "\en.txt")
Dim line As String = Nothing
While (InlineAssignHelper(line, reader.ReadLine())) IsNot Nothing
Dim pat = String.Format("\b({0})\b", line)
_textInput = Regex.Replace(_textInput , pat, line)
End While
End Using
BackgroundWorker1.ReportProgress(i)
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
ProgressBar1.Value = e.ProgressPercentage
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("done")
RichTextBox1.Text = _textInput
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
Your Pastebin link includes the following code:
For i = 0 To 100
Threading.Thread.Sleep(200)
[...]
Next
At a glance, why are you putting the thread to sleep for a fifth of a second on every iteration of the for-loop?
Remove this line for starters.

Save changes made to file names in folder. All 762 of them

I downloaded a pack of roms for a SNES emulator and when I went to transfer them over I received an error on the illegal file names. So I started coding a simple app that will remove the problem char from the roms title. I got that part figured out however I cannot figure out how to save the edited file names. Keep in mind there are 762 roms in the folder so manually doing this is not an option. Thanks in advance for any guidance.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.AddRange(IO.Directory.GetFiles("c:\ROMS"))
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Index As Integer = ListBox1.SelectedIndex
Dim Results = (From T In ListBox1.Items
Select System.Text.RegularExpressions.Regex.Replace(CStr(T),
"[""]", String.Empty).Replace("[!]", "")
).ToArray
ListBox1.Items.Clear()
ListBox1.Items.AddRange(Results)
If Index <> -1 Then
ListBox1.SelectedIndex = Index
End If
End Sub
End Class
I am using button1 to open the folder into a listbox.
Button 2 removes the unwanted [!] from the title
Button 3 would be where the save feature is.
####### EDIT #####
I figured out what the real problem was for my particular case.
I was transferring the folder of roms over to my Xbox and apparently the is a character limit not so much a restriction on chars used. Dont know the actual allowed amount of chars to be used but for anyone who may be trying to do what I did just use my code to remove unnecessary chars in the title.
Add another Listbox to your form called Listbox2 then use this code below. Also notice in Button2 the use of GetDirectoryName and GetFileName so that you don't replace any chars in the folder name...only the filename
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.AddRange(IO.Directory.GetFiles("c:\ROMS"))
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Index As Integer = ListBox1.SelectedIndex
Dim Results = (From T In ListBox1.Items
Select IO.Path.GetDirectoryName(CStr(T)) & "\" & System.Text.RegularExpressions.Regex.Replace(IO.Path.GetFileName(CStr(T)),
"[""]", String.Empty).Replace("[!]", "")
).ToArray
ListBox2.Items.Clear()
ListBox2.Items.AddRange(Results)
If Index <> -1 Then
ListBox1.SelectedIndex = Index
ListBox2.SelectedIndex = Index
End If
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
For x As Integer = 0 To Me.ListBox1.Items.Count - 1
IO.File.Move(Me.ListBox1.Items(x), Me.ListBox2.Items(x))
Next
MsgBox("Done!")
End Sub
End Class