How to create a progress bar that updates simultaneously with a file transfer - vb.net

As the title implies, I am trying to create a progress bar that updates with a file transfer. I am currently using Visual Studio 2019. I have been through dozens of articles and videos all claiming to do just this. After many days of testing, I have gotten close, but the progress bar will still only update after the file transfer is complete. I am using multi threading techniques to accomplish just this much. I would very much appreciate if someone could just lay it down for me on how to do this. Here is my code so far. It doesn't really help for making it but you can at least see what I am trying to achieve. I also left out some large chunks of commented out test script.
Summary of what I need to is: Create a script that will copy the specified directory and all sub directories. While doing this I would like the progress bar to move with the file transfer.
Imports System.ComponentModel
Imports System.Threading
Imports System
Imports System.IO
Public Class Form1
Private Sub BtnStartTransfer_Click(sender As Object, e As EventArgs) Handles btnStartTransfer.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Delegate Sub DelegateProgressBarMax(ByVal check As Integer)
Private Sub ProgressBarUpdate(ByVal check As Integer)
If pBar1.InvokeRequired = True Then
Invoke(Sub() pBar1.Value = check)
Else
pBar1.Value = check
End If
End Sub
Private Delegate Sub DelegateUpdateOutput(ByVal check2 As String)
Private Sub OutputUpdate(ByVal check2 As String)
If txtOutput.InvokeRequired = True Then
Invoke(Sub() txtOutput.Text = txtOutput.Text & check2 & Environment.NewLine)
Else
txtOutput.Text = txtOutput.Text & check2
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim getCopyFrom As String = txtCopyFrom.Text
Dim getCopyTo As String = txtCopyTo.Text
Dim splitUser() As String = getCopyFrom.Split("\")
Dim finalValue As String = splitUser.Length - 1
Dim stringValue As String = CStr(splitUser(finalValue))
Dim getUser As String
'If MsgBox("Is this the correct user?: " & stringValue, vbYesNo + vbQuestion) = vbYes Then
' getUser = stringValue
'Else
' getUser = InputBox("Enter in the correct Username")
'End If
Dim checkCopyFrom As New IO.DirectoryInfo(getCopyFrom)
Dim checkCopyTo As New IO.DirectoryInfo(getCopyTo)
If checkCopyFrom.Exists Then
Else
MsgBox("The location you are trying to copy from does not exist.")
Exit Sub
End If
If checkCopyTo.Exists Then
Else
MsgBox("The location you are trying to copy to does not exist.")
Exit Sub
End If
'Copying the Desktop folder
Dim dirDesktop = getCopyFrom & "\Desktop"
Dim getDir = IO.Directory.GetFiles(dirDesktop, "*", IO.SearchOption.AllDirectories)
Dim fileTotal As Integer = getDir.Length
Dim filesTransferred As Integer = 0
Dim di As New DirectoryInfo(dirDesktop)
Dim fiArr As FileInfo() = di.GetFiles("*", SearchOption.AllDirectories)
Dim diArr As DirectoryInfo() = di.GetDirectories("*", IO.SearchOption.AllDirectories)
Dim fri As FileInfo
Dim fol As DirectoryInfo
For Each fri In fiArr
filesTransferred += 1
BackgroundWorker1.ReportProgress(CInt(filesTransferred * 100 \ fiArr.Length), True)
OutputUpdate(fri.Name)
'File.Copy(dirDesktop & "\" & fri.Name, getCopyTo & "\" & fri.Name, True)
'My.Computer.FileSystem.CopyDirectory(getCopyFrom & "\Desktop", getCopyTo & "\Users\" & getUser & "\Desktop", False)
Next fri
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
pBar1.Value = e.ProgressPercentage
End Sub

Related

Copy a File Using DragDrop VB.Net

What is wrong with my code? Getting a 'Process cannot access the file because it is being used by another process' error msg Is there a way around this. My google-fu was not giving me much luck. I was not able to Move or Copy, and I will take either.
Private Sub frmFiberTransMain_DragEnter(sender As Object, e As DragEventArgs) Handles MyBase.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop, False) = True Then
e.Effect = DragDropEffects.All
End If
End Sub
Private Sub frmFiberTransMain_DragDrop(sender As Object, e As DragEventArgs) Handles MyBase.DragDrop
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
Dim filePaths As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
Call CopyFileDrop(filePaths)
End If
End Sub
Private Sub CopyFileDrop(filePaths As String())
For Each fileLoc As String In filePaths
Dim fileName As String = fileLoc
Dim fi As New IO.FileInfo(fileName)
File.Create(fileName)
Dim justFileName As String = fi.Name
Dim newPathName As String = gProgDir & "\" & justFileName
Directory.Move(fileLoc, newPathName)
Next fileLoc
End Sub
File.Create(fileName) returns an open handle and you're not closing it. It doesn't look like you need that line. –
#LarsTech 50 mins ago

How to get line number from a text file in vb.net

I am making a program where i have 2 text files and i want 2 get one line from each text file like this
Dim pathlocal as string= Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Test\"
Dim reader As New System.IO.StreamReader(pathlocal & "to.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
For Each file In allLines
If pathlocal & "from.txt".Contains(My.Computer.FileSystem.GetFileInfo(file).Name) Then
'Get line number of from.txt where you found file.name
End If
End If
Next
I appreciate the help(and pls try 2 make it simple sorry but i am not that good THANX)
This might help you:
Imports System.IO
Imports System
Imports System.Collections.Generic
Public Class Form1
Dim path As String = "Your Path"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim indxto As Integer = 0
Dim indxfrom As Integer = 0
Dim allLinesto As List(Of String) = File.ReadAllLines(path & "\" & "to.txt").ToList
Dim allLinesfrom As List(Of String) = File.ReadAllLines(path & "\" & "from.txt").ToList
For Each line As String In allLinesto
indxto = allLinesto.IndexOf(line)
'Debug.Print(line & " " & indxto.ToString)
For Each item As String In allLinesfrom
indxfrom = allLinesto.IndexOf(item)
If line = item Then
Debug.Print(item & " " & indxfrom.ToString)
End If
Next
Next
End Sub
End Class
You can instantiate a couple of Integer typed variables to help with this. One stores the line number as you iterate through the list and the other stores the line number you are seeking. Plus, by changing your For Each approach to a Do Until or Do While approach you could potentially speed things up if the target is found prior to the last line of the file.
Dim intLineNumber As Integer = -1
Dim intLineCursor As Integer
Do Until (intLineCursor = allLines.Count OrElse intLineNumber <> -1)
If pathlocal & "from.txt".Contains(My.Computer.FileSystem.GetFileInfo(allLines(intLineCursor)).Name) Then
intLineNumber = intLineCursor '+ 1 if you are displaying to a user since the lower bound is 0 based.
End If
'Increment the cursor variable.
intLineCursor += 1
Loop

Variable 'details' is used before it has been assigned a value.

Variable details is used before it has been assigned a value. What is the problem with details?
Option Explicit On
Imports System.Text
Imports System.IO
Public Class Main
Private SelectedItem As ListViewItem
Dim data As String
Dim strpriority As String
Dim task As String
Dim createdate As String
Dim duedate As String
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
AddTask.Show()
Me.Hide()
End Sub
Private Sub HistoryToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HistoryToolStripMenuItem.Click
History.Show()
Me.Hide()
End Sub
Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim fpath As String
Dim splitdata
fpath = AppDomain.CurrentDomain.BaseDirectory
Dim filepath As String
filepath = fpath & "task.txt"
Dim details As String
details = My.Computer.FileSystem.ReadAllText(filepath)
splitdata = Split(details, vbCrLf)
Dim i As Integer
For i = 0 To UBound(splitdata)
lblTaskName.Items.Add(splitdata(i))
Next
lblTime.Enabled = True
Timer1.Interval = 10
Timer1.Enabled = True
lblDate.Text = DateTime.Now.ToString("dd MMMM yyyy")
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
lblTime.Text = TimeOfDay
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
If lblTaskName.SelectedItem = "" Then
MsgBox("Please select a record")
Else
If lblTaskName.Items.Count > 0 Then
If MessageBox.Show("Do you really want to delete this record?", "Delete", MessageBoxButtons.YesNo) = MsgBoxResult.Yes Then
lblTaskName.Items.Remove(lblTaskName.SelectedItem.ToString())
Else
MessageBox.Show("Operation Cancelled")
End If
End If
End If
Try
Dim fpath As String
fpath = AppDomain.CurrentDomain.BaseDirectory
Dim filepath As String
filepath = fpath & "task.txt"
Dim details As String
If lblTaskName.Items.Count > 0 Then
details = lblTaskName.Items(0)
Dim i As Integer
For i = 1 To lblTaskName.Items.Count - 1
details = details & vbCrLf & lblTaskName.Items(i)
Next
End If
My.Computer.FileSystem.WriteAllText(filepath, details, False)
Catch ex As Exception
MsgBox("Values Can't be inserted this time")
End Try
End Sub
Private Function filepaths() As String
Throw New NotImplementedException
End Function
End Class
The problem is in the btnRemove_Click method in this part:
Dim details As String
If lblTaskName.Items.Count > 0 Then
details = lblTaskName.Items(0)
If the condition evaluates to false, the details variable is used before it is initialized, because it is only set in the if block up to now.
I suppose you want to move the following line into the if block to solve the problem:
My.Computer.FileSystem.WriteAllText(filepath, details, False)
Alternatively, you can come up with a default value for details so that it is set in any case. For performance reasons, you can set the default value (e.g. a text or String.Empty) in an else branch:
Dim details As String
If lblTaskName.Items.Count > 0 Then
' ...
Else
details = "Default Value"
End If
You need to think through the flow of your program. Consider this code:
Dim details As String
If lblTaskName.Items.Count > 0 Then
details = lblTaskName.Items(0)
Dim i As Integer
For i = 1 To lblTaskName.Items.Count - 1
details = details & vbCrLf & lblTaskName.Items(i)
Next
End If
My.Computer.FileSystem.WriteAllText(filepath, details, False)
You declare the details variable at the top. Then you check that there is at least 1 item in the lblTaskName control. If that test passes, then you assign the first item to details. But what if that test doesn't pass? What if there are 0 items in the lblTaskName control? In that case, the interior of the If block never runs, and nothing ever gets stored in details. Then in the final line, you try to use the value of the details variable *outside of the If block. This is illegal because it may not have been assigned a value.
Perhaps you meant for that WriteAllText line to be inside of If block? Otherwise, you'll need to add an Else clause to your If statement to handle the case where there are 0 items in lblTaskName.
Aside from that, stylistically speaking, you should prefer to initialize variables at the time of declaration whenever possible. So for example, instead of writing:
Dim fpath As String
Dim splitdata
fpath = AppDomain.CurrentDomain.BaseDirectory
Dim filepath As String
filepath = fpath & "task.txt"
Dim details As String
details = My.Computer.FileSystem.ReadAllText(filepath)
splitdata = Split(details, vbCrLf)
write it as:
Dim fpath As String = AppDomain.CurrentDomain.BaseDirectory
Dim filepath As String = fpath & "task.txt"
Dim details As String = My.Computer.FileSystem.ReadAllText(filepath)
Dim splitdata() As String = Split(details, vbCrLf)
(I'm OCD, so I line up my equals signs. That part is totally optional.)
It doesn't make the code run any faster, but it does make it easier to read! More importantly, it decreases the potential for bugs.

Assistance with Copy & Paste VB System

The system is meant to work so that whenever the gta_sa process stops running, it copies the file selected when browsing cmdFile to cmdStorage's location. Problem I have right now is that it doesn't store the new file in .txt, but rather just as .file. It's openable, but not as default.
Also, I wasn't sure how to do the detection on when gtasa process was recently closed so I had to use if the process is active. I'd really appreciate it for some help, thanks.**
EDIT: Maybe it needs to use a timer? Not sure, thanks again.
Imports System.Diagnostics
Imports System Imports System.ComponentModel
Public Class frmChatLog
Dim ofdDone
Dim fldDone
Dim Completed
Private Sub cmdStorage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdStorage.Click
Using fld As New FolderBrowserDialog()
If fld.ShowDialog() = Windows.Forms.DialogResult.OK Then
MessageBox.Show("Selected " & fld.SelectedPath)
fldDone = fld.SelectedPath
cmdStorage.Enabled = False
End If
End Using
End Sub
Private Sub cmdFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdFile.Click
Using ofd As New OpenFileDialog()
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
MessageBox.Show("Selected " & ofd.FileName)
ofdDone = ofd.FileName
cmdFile.Enabled = False
End If
End Using
End Sub
Private Sub cmdStart_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdStart.Click
If cmdFile.Enabled = False And cmdStorage.Enabled = False Then
Do Until Process.GetProcessesByName("gta_sa").Count > 0
If Process.GetProcessesByName("gta_sa").Count > 0 Then
MsgBox("Game is on")
Else
System.IO.File.Move(ofdDone, fldDone & "\" & Today.Now.ToString("ddMMyyHHmmss"))
Completed = fldDone & "\" & Today.Now.ToString("ddMMyyHHmmss")
Completed.ChangeExtension(".txt")
Exit Do
End If
Loop
End If
End Sub
End Class
Problem I have right now is that it doesn't store the new file in .txt, but rather just as .file.
To fix that, change this line near the bottom of your code:
System.IO.File.Move(ofdDone, fldDone & "\" & Today.Now.ToString("ddMMyyHHmmss"))
to this:
File.Move(ofdDone, Path.Combine(fldDone, Now.ToString("ddMMyyHHmmss") & ".txt"))
Then get rid of any line that mentions your Completed variable. You may also need to add an Imports System.IO to the top of the file.

ThreadState always is "Unstarted"

When I start a thread, the ThreadState always is "Unstarted" even if I do a "Thread.Abort()", my thread starts and finish the work good... I don't know why I get that always the same state.
Dim thread_1 As System.Threading.Thread = New Threading.Thread(AddressOf mithread)
thread_1.Start()
System.Threading.Thread.Sleep(100)
While not thread_1.ThreadState = Threading.ThreadState.Running
MsgBox(thread_1.ThreadState.ToString) ' "Unstarted"
thread_1.Abort()
MsgBox(thread_1.ThreadState.ToString) ' "Unstarted" again and again...
End While
UPDATE
This is the sub who calls the thread, and the problem is the "while" statament is not waiting,
PS: You can see a comment explanation at the middle of this sub:
public sub...
...
If Not playerargs = Nothing Then
If randomize.Checked = True Then
Dim thread_1 As System.Threading.Thread = New Threading.Thread(AddressOf mithread)
thread_1.Start()
System.Threading.Thread.Sleep(50)
While thread_1.ThreadState = Threading.ThreadState.Running
Windows.Forms.Application.DoEvents()
End While
Else
progresslabel.Text = "All files added..."
End If
' HERE IS THE PROBLEM, IF I CHECK "AUTOCLOSE" CHECKBOX THEN,
' THE FORM ALWAYS TRY TO CLOSE BEFORE THREAD IS COMPLETED:
' -----------------------------------------
If autoclose.Checked = True Then Me.Close()
'------------------------------------------
Else
...
End Sub
And here is the "mithread" thread:
Public Sub mithread()
Dim Str As String
Dim Pattern As String = ControlChars.Quote
Dim ArgsArray() As String
Str = Replace(playerargs, " " & ControlChars.Quote, "")
ArgsArray = Split(Str, Pattern)
Using objWriter As New System.IO.StreamWriter(Temp_file, False, System.Text.Encoding.UTF8)
Dim n As Integer = 0
Dim count As Integer = 0
Dim foldercount As Integer = -1
For Each folder In ArgsArray
foldercount += 1
If foldercount > 1 Then
InvokeControl(ProgBarPlus1, Sub(x) x.Max = foldercount)
End If
Next
If foldercount = 1 Then
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
InvokeControl(ProgBarPlus1, Sub(x) x.Max = files.Count)
For Each file In files
n += 1
CheckPrimeNumber(n)
count += 1
If file.Extension.ToLower = ".lnk" Then
Dim ShotcutTarget As String = Shortcut.ResolveShortcut((file.FullName).ToString())
objWriter.Write(ShotcutTarget & vbCrLf)
Else
objWriter.Write(file.FullName & vbCrLf)
End If
Next
End If
Next
ElseIf foldercount > 1 Then
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
InvokeControl(ProgBarPlus1, Sub(x) x.Value += 1)
For Each file In files
If file.Extension.ToLower = ".lnk" Then
Dim ShotcutTarget As String = Shortcut.ResolveShortcut((file.FullName).ToString())
objWriter.Write(ShotcutTarget & vbCrLf)
Else
objWriter.Write(file.FullName & vbCrLf)
End If
Next
End If
Next
End If
End Using
If Not thread_1.ThreadState = Threading.ThreadState.AbortRequested Then
MsgBox(thread_1.ThreadState.ToString)
Randomize_a_file.RandomizeFile(Temp_file)
InvokeControl(ProgBarPlus1, Sub(x) x.Value = 0)
' Process.Start(userSelectedPlayerFilePath, ControlChars.Quote & Temp_file.ToString() & ControlChars.Quote)
InvokeControl(progresslabel, Sub(x) x.Text = "All files launched...")
End If
End Sub
Its not easy to work out what your problem is, but i can say for sure a While Loop and DoEvents is not the way forward at all.
Instead raise an event when the thread has done all its work, subscribe to the event, and when it is raise close the form (if autoclose = true):
Public Class Form1
Public Event threadCompleted()
Public Sub New()
InitializeComponent()
AddHandler threadCompleted, AddressOf Me.Thread_Completed
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim t1 As New Threading.Thread(AddressOf mithread)
t1.Start()
End Sub
Public Sub mithread()
'simulate some work:
Threading.Thread.Sleep(3000)
'then raise the event when done
RaiseEvent threadCompleted()
End Sub
Public Delegate Sub Thread_CompletedDelegate()
Private Sub Thread_Completed()
If Me.InvokeRequired Then
Me.BeginInvoke(New Thread_CompletedDelegate(AddressOf Thread_Completed))
Else
If autoclose.Checked = True Then
Me.Close()
End If
End If
End Sub
End Class
Or use a background worker which does all this, plus handles reporting progress and cancelation all for you.
Sounds like something is happening in mithread that is preventing the thread from fully starting. I ran similar code with an empty sub for mithread and I get the expected threadstate (Stopped then Aborted).
Sub Main()
Dim thread_1 As System.Threading.Thread = New Threading.Thread(AddressOf mithread)
thread_1.Start()
System.Threading.Thread.Sleep(100)
While Not thread_1.ThreadState = Threading.ThreadState.Running
Console.WriteLine(thread_1.ThreadState.ToString)
thread_1.Abort()
Console.WriteLine(thread_1.ThreadState.ToString)
If thread_1.ThreadState = Threading.ThreadState.Aborted Then Exit While
End While
End Sub
Sub mithread()
End Sub