real-time output of process in vb.net - vb.net

I have the following class for diskparting and imaging a pc. The form has a regular text box (tb1) that lists each step of the process (output) and a rich text box (rtb1) that outputs real time process info. The problem I'm having is the app isn't waiting for the real time output to finish before starting the next sub routine. See attached code:
Imports System
Imports System.IO
Imports System.Management
Imports System.Text.RegularExpressions
Public Class Form1
Private Property pcSerial As Object = GetBiosSerialNumber()
Private Property title As String = "Ross PC Imaging"
Private Property pcModel As Object
Private Property wkstn As String
Private Property srvr As Object
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Call ross()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call ross()
End Sub
Private Sub ross()
Dim objCS As ManagementObjectSearcher
Dim objMgmt As ManagementObject
objCS = New ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem")
For Each objMgmt In objCS.Get
pcModel = objMgmt("model").ToString()
Next
Output(pcModel)
Output(pcSerial)
'Map network drive
Call MapDrive()
'Diskpart
Output("[ " & Now & " ] PC - " & pcSerial & " physical drives being partitioned and formatted")
If pcModel = "Server" Then
Call diskpart("srvr")
Else
Call diskpart("wkstn")
End If
Output("[ " & Now & " ] PC - " & pcSerial & " physical drives have been partitioned and formatted")
Dim msgDiskPart As String : msgDiskPart = ("[ " & Now & " ] PC - " & pcSerial & " physical drives partitioned and formatted")
Call WriteToLog(title, msgDiskPart)
'Dism
Output("[ " & Now & " ] PC - " & pcSerial & " imaging started")
If pcModel = "Server" Then
Call dism("srvr")
Else
Call dism("wkstn")
End If
Output("[ " & Now & " ] PC - " & pcSerial & " imaging completed")
Dim msgImgStop As String : msgImgStop = ("[ " & Now & " ] PC - " & pcSerial & " imaged")
Call WriteToLog(title, msgImgStop)
'Reboot
'Call reboot()
End Sub
Private Sub MapDrive()
'Map network drive
Dim map As New Process()
map.StartInfo.FileName = "net.exe"
map.StartInfo.Arguments = " use t: \\172.47.3.254\wims"
map.StartInfo.CreateNoWindow = True
map.StartInfo.UseShellExecute = False
map.StartInfo.RedirectStandardOutput = True
map.Start()
map.WaitForExit()
End Sub
Private Sub diskpart(ByVal pctype As String)
'Diskpart disk partitioning
Dim dp As New Process()
dp.StartInfo.FileName = "diskpart.exe"
dp.StartInfo.Arguments = " /s x:\" & pctype & "_diskpart.txt"
dp.StartInfo.CreateNoWindow = True
dp.StartInfo.UseShellExecute = False
dp.StartInfo.RedirectStandardOutput = True
dp.StartInfo.RedirectStandardError = True
dp.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dp.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dp.OutputDataReceived, AddressOf proc_OutputDataReceived
dp.Start()
dp.BeginErrorReadLine()
dp.BeginOutputReadLine()
End Sub
Private Sub dism(ByVal imgFile As String)
'Image C Drive
Dim dismC As New Process
dismC.StartInfo.FileName = "dism.exe"
dismC.StartInfo.Arguments = " /Apply-Image /ImageFile:t:\" & imgFile & ".wim /index:1 /ApplyDir:c:\"
dismC.StartInfo.CreateNoWindow = True
dismC.StartInfo.UseShellExecute = False
dismC.StartInfo.RedirectStandardOutput = True
dismC.StartInfo.RedirectStandardError = True
dismC.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dismC.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dismC.OutputDataReceived, AddressOf proc_OutputDataReceived
dismC.Start()
dismC.BeginErrorReadLine()
dismC.BeginOutputReadLine()
dismC.Close()
'Image D Drive
Dim dismD As New Process
dismD.StartInfo.FileName = "dism.exe"
dismD.StartInfo.Arguments = " /Apply-Image /ImageFile:t:\" & imgFile & ".wim /index:2 /ApplyDir:d:\"
dismD.StartInfo.CreateNoWindow = True
dismD.StartInfo.UseShellExecute = False
dismD.StartInfo.RedirectStandardOutput = True
dismD.StartInfo.RedirectStandardError = True
dismD.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dismD.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dismD.OutputDataReceived, AddressOf proc_OutputDataReceived
dismD.Start()
dismD.BeginErrorReadLine()
dismD.BeginOutputReadLine()
dismD.Close()
End Sub
Private Sub reboot()
'Reboots a pc while in WinPE
Dim reset As New Process
reset.StartInfo.FileName = "wpeutils.exe"
reset.StartInfo.Arguments = " reboot"
reset.Start()
End Sub
Private Sub WriteToLog(ByVal title As String, ByVal msg As String)
'Check and make directory
If Not System.IO.Directory.Exists("t:\logs\") Then
System.IO.Directory.CreateDirectory("t:\logs\")
End If
'Check and make file
Dim fs As FileStream = New FileStream("t:\logs\" & pcSerial & ".log", FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim s As StreamWriter = New StreamWriter(fs)
s.Close()
fs.Close()
'Logging
Dim fs1 As FileStream = New FileStream("t:\logs\" & pcSerial & ".log", FileMode.Append, FileAccess.Write)
Dim s1 As StreamWriter = New StreamWriter(fs1)
s1.Write("Title: " & title & vbCrLf)
s1.Write("Message: " & msg & vbCrLf)
s1.Write("================================================" & vbCrLf)
s1.Close()
fs1.Close()
End Sub
Private Sub Output(s As String)
'Output to form window
If s <> "" Then
tb1.AppendText(vbCrLf & ">> " & s)
End If
End Sub
Public ReadOnly Property Model()
Get
Model = pcModel
End Get
End Property
Public Function GetBiosSerialNumber() As String
Dim OutputString As String = String.Empty
Using Process As New Process
AddHandler Process.OutputDataReceived,
Sub(sender As Object, e As DataReceivedEventArgs)
OutputString = OutputString & e.Data & vbCrLf
End Sub
With Process.StartInfo
.FileName = "cmd"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
End With
With Process
.Start()
.BeginOutputReadLine()
End With
Using InputStream As System.IO.StreamWriter = Process.StandardInput
With InputStream
.AutoFlush = True
.Write("wmic bios get serialnumber" & vbCrLf)
End With
End Using
Do
Application.DoEvents()
Loop Until Process.HasExited
End Using
Return Replace(OutputString.Split(CChar(vbCrLf)).ToList(6).Substring(1), " ", "")
End Function
Delegate Sub UpdateTextBoxDelg(text As String)
Public myDelegate As UpdateTextBoxDelg = New UpdateTextBoxDelg(AddressOf UpdateTextBox)
Public Sub UpdateTextBox(text As String)
rtb1.Text += text & Environment.NewLine
rtb1.SelectionStart = rtb1.Text.Length
rtb1.ScrollToCaret()
End Sub
Public Sub proc_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
If Me.InvokeRequired = True Then
Me.Invoke(myDelegate, e.Data)
Else
UpdateTextBox(e.Data)
End If
End Sub
End Class
I appreciate any advice.

Imports System
Imports System.IO
Imports System.Management
Imports System.Text.RegularExpressions
Public Class Form1
Delegate Sub UpdateTextBoxDelg(text As String)
Public myDelegate As UpdateTextBoxDelg = New UpdateTextBoxDelg(AddressOf UpdateTextBox)
Private Property pcSerial As Object = GetBiosSerialNumber()
Private Property title As String = "Ross PC Imaging"
Private Property pcModel As Object
Private Property wkstn As String
Private Property srvr As Object
Private Property pctype As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ross()
End Sub
Private Sub ross()
Dim objCS As ManagementObjectSearcher
Dim objMgmt As ManagementObject
objCS = New ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem")
For Each objMgmt In objCS.Get
pcModel = objMgmt("model").ToString()
Next
Output(pcModel)
Output(pcSerial)
'Map network drive
DriveMap.RunWorkerAsync()
End Sub
Private Sub DriveMap_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles DriveMap.DoWork
'Map network drive
Dim map As New Process()
map.StartInfo.FileName = "net.exe"
map.StartInfo.Arguments = " use t: \\172.47.3.254\wims"
map.StartInfo.CreateNoWindow = True
map.StartInfo.UseShellExecute = False
map.StartInfo.RedirectStandardOutput = True
map.Start()
map.WaitForExit()
End Sub
Private Sub DriveMap_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles DriveMap.RunWorkerCompleted
Output("[ " & Now & " ] PC - *" & pcSerial & "* - partitioning and formatting drives")
Dim msgDiskPart As String : msgDiskPart = ("[ " & Now & " ] PC - *" & pcSerial & "* - partitioning and formatting drives")
Call WriteToLog(title, msgDiskPart)
DiskPart.RunWorkerAsync()
End Sub
Private Sub DiskPart_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles DiskPart.DoWork
If pcModel = "Server" Then
pctype = "srvr"
Else
pctype = "wkstn"
End If
'Diskpart disk partitioning
Dim dp As New Process()
dp.StartInfo.FileName = "diskpart.exe"
dp.StartInfo.Arguments = " /s x:\" & pctype & "_diskpart.txt"
dp.StartInfo.CreateNoWindow = True
dp.StartInfo.UseShellExecute = False
dp.StartInfo.RedirectStandardOutput = True
dp.StartInfo.RedirectStandardError = True
dp.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dp.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dp.OutputDataReceived, AddressOf proc_OutputDataReceived
dp.Start()
dp.BeginErrorReadLine()
dp.BeginOutputReadLine()
dp.WaitForExit()
End Sub
Private Sub DiskPart_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles DiskPart.RunWorkerCompleted
Output("[ " & Now & " ] PC - *" & pcSerial & "* - drives have been partitioned and formatted")
Dim msgDiskPart As String : msgDiskPart = ("[ " & Now & " ] PC - *" & pcSerial & "* - drives have been partitioned and formatted")
Call WriteToLog(title, msgDiskPart)
Output("[ " & Now & " ] PC - *" & pcSerial & "* - running disk check on drive C")
Dim msgChkDskC As String : msgChkDskC = ("[ " & Now & " ] PC - *" & pcSerial & "* - running disk check on drive C")
Call WriteToLog(title, msgChkDskC)
ChkDskC.RunWorkerAsync()
End Sub
Private Sub ChkDskC_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles ChkDskC.DoWork
Dim dc As New Process
dc.StartInfo.FileName = "chkdsk.exe"
dc.StartInfo.Arguments = " c: /f"
dc.StartInfo.CreateNoWindow = True
dc.StartInfo.UseShellExecute = False
dc.StartInfo.RedirectStandardOutput = True
dc.StartInfo.RedirectStandardError = True
dc.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dc.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dc.OutputDataReceived, AddressOf proc_OutputDataReceived
dc.Start()
dc.BeginErrorReadLine()
dc.BeginOutputReadLine()
dc.WaitForExit()
End Sub
Private Sub ChkDskC_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles ChkDskC.RunWorkerCompleted
Output("[ " & Now & " ] PC - *" & pcSerial & "* - drive C had no errors")
Dim msgChkDskC As String : msgChkDskC = ("[ " & Now & " ] PC - *" & pcSerial & "* - drive C had no errors")
Call WriteToLog(title, msgChkDskC)
Output("[ " & Now & " ] PC - *" & pcSerial & "* - running disk check on drive D")
Dim msgChkDskD As String : msgChkDskD = ("[ " & Now & " ] PC - *" & pcSerial & "* - running disk check on drive D")
Call WriteToLog(title, msgChkDskD)
ChkDskD.RunWorkerAsync()
End Sub
Private Sub ChkDskD_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles ChkDskD.DoWork
Dim dc As New Process
dc.StartInfo.FileName = "chkdsk.exe"
dc.StartInfo.Arguments = " d: /f"
dc.StartInfo.CreateNoWindow = True
dc.StartInfo.UseShellExecute = False
dc.StartInfo.RedirectStandardOutput = True
dc.StartInfo.RedirectStandardError = True
dc.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dc.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dc.OutputDataReceived, AddressOf proc_OutputDataReceived
dc.Start()
dc.BeginErrorReadLine()
dc.BeginOutputReadLine()
dc.WaitForExit()
End Sub
Private Sub ChkDskD_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles ChkDskD.RunWorkerCompleted
Output("[ " & Now & " ] PC - *" & pcSerial & "* - drive D had no errors")
Dim msgChkDskD As String : msgChkDskD = ("[ " & Now & " ] PC - *" & pcSerial & "* - drive D had no errors")
Call WriteToLog(title, msgChkDskD)
Output("[ " & Now & " ] PC - *" & pcSerial & "* - imaging C drive")
Dim msgDismC As String : msgDismC = ("[ " & Now & " ] PC - *" & pcSerial & "* - imaging C drive")
Call WriteToLog(title, msgDismC)
DismC.RunWorkerAsync()
End Sub
Private Sub DismC_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles DismC.DoWork
If pcModel = "Server" Then
pctype = "srvr"
Else
pctype = "wkstn"
End If
'Image C Drive
Dim dismC As New Process
dismC.StartInfo.FileName = "dism.exe"
dismC.StartInfo.Arguments = " /Apply-Image /ImageFile:t:\" & pctype & ".wim /index:1 /ApplyDir:c:\"
dismC.StartInfo.CreateNoWindow = True
dismC.StartInfo.UseShellExecute = False
dismC.StartInfo.RedirectStandardOutput = True
dismC.StartInfo.RedirectStandardError = True
dismC.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dismC.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dismC.OutputDataReceived, AddressOf proc_OutputDataReceived
dismC.Start()
dismC.BeginErrorReadLine()
dismC.BeginOutputReadLine()
dismC.WaitForExit()
End Sub
Private Sub DismC_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles DismC.RunWorkerCompleted
Output("[ " & Now & " ] PC - *" & pcSerial & "* - drive C imaged")
Dim msgDismC As String : msgDismC = ("[ " & Now & " ] PC - *" & pcSerial & "* - drive C imaged")
Call WriteToLog(title, msgDismC)
Output("[ " & Now & " ] PC - *" & pcSerial & "* - imaging D drive")
Dim msgDismD As String : msgDismD = ("[ " & Now & " ] PC - *" & pcSerial & "* - imaging D drive")
Call WriteToLog(title, msgDismD)
DismD.RunWorkerAsync()
End Sub
Private Sub DismD_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles DismD.DoWork
If pcModel = "Server" Then
pctype = "srvr"
Else
pctype = "wkstn"
End If
'Image D Drive
Dim dismD As New Process
dismD.StartInfo.FileName = "dism.exe"
dismD.StartInfo.Arguments = " /Apply-Image /ImageFile:t:\" & pctype & ".wim /index:2 /ApplyDir:d:\"
dismD.StartInfo.CreateNoWindow = True
dismD.StartInfo.UseShellExecute = False
dismD.StartInfo.RedirectStandardOutput = True
dismD.StartInfo.RedirectStandardError = True
dismD.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dismD.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dismD.OutputDataReceived, AddressOf proc_OutputDataReceived
dismD.Start()
dismD.BeginErrorReadLine()
dismD.BeginOutputReadLine()
dismD.WaitForExit()
End Sub
Private Sub DismD_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles DismD.RunWorkerCompleted
Output("[ " & Now & " ] PC - *" & pcSerial & "* - drive D imaged")
Dim msgDismD As String : msgDismD = ("[ " & Now & " ] PC - *" & pcSerial & "* - drive D imaged")
Call WriteToLog(title, msgDismD)
Output("[ " & Now & " ] PC - *" & pcSerial & "* - imaging complete, rebooting")
'Call reboot()
End Sub
Private Sub reboot()
'Reboots a pc while in WinPE
Dim reset As New Process
reset.StartInfo.FileName = "wpeutils.exe"
reset.StartInfo.Arguments = " shutdown"
reset.Start()
End Sub
Private Sub WriteToLog(ByVal title As String, ByVal msg As String)
'Check and make directory
If Not System.IO.Directory.Exists("t:\logs\") Then
System.IO.Directory.CreateDirectory("t:\logs\")
End If
'Check and make file
Dim fs As FileStream = New FileStream("t:\logs\" & pcSerial & ".log", FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim s As StreamWriter = New StreamWriter(fs)
s.Close()
fs.Close()
'Logging
Dim fs1 As FileStream = New FileStream("t:\logs\" & pcSerial & ".log", FileMode.Append, FileAccess.Write)
Dim s1 As StreamWriter = New StreamWriter(fs1)
s1.Write("Title: " & title & vbCrLf)
s1.Write("Message: " & msg & vbCrLf)
s1.Write("================================================" & vbCrLf)
s1.Close()
fs1.Close()
End Sub
Private Sub Output(s As String)
'Output to form window
If s <> "" Then
tb1.AppendText(vbCrLf & ">> " & s)
End If
End Sub
Public ReadOnly Property Model()
Get
Model = pcModel
End Get
End Property
Public Function GetBiosSerialNumber() As String
Dim OutputString As String = String.Empty
Using Process As New Process
AddHandler Process.OutputDataReceived,
Sub(sender As Object, e As DataReceivedEventArgs)
OutputString = OutputString & e.Data & vbCrLf
End Sub
With Process.StartInfo
.FileName = "cmd"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
End With
With Process
.Start()
.BeginOutputReadLine()
End With
Using InputStream As System.IO.StreamWriter = Process.StandardInput
With InputStream
.AutoFlush = True
.Write("wmic bios get serialnumber" & vbCrLf)
End With
End Using
Do
Application.DoEvents()
Loop Until Process.HasExited
End Using
Return Replace(OutputString.Split(CChar(vbCrLf)).ToList(6).Substring(1), " ", "")
End Function
Public Sub UpdateTextBox(text As String)
rtb1.Text += text & Environment.NewLine
rtb1.SelectionStart = rtb1.Text.Length
rtb1.ScrollToCaret()
End Sub
Public Sub proc_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
If Me.InvokeRequired = True Then
Me.Invoke(myDelegate, e.Data)
Else
UpdateTextBox(e.Data)
End If
End Sub
End Class

Related

The process cannot access the file 'path' because it is being used by another process when use FileSystemWatcher

I have trouble creating excel or word files in folders that need to be tracked. If creating continuously using a regular new file right at the home directory trace, it will report an error like this.
I use the filesystemwatcher to keep track of the file
Here is my code
Public Sub Createee(sender As Object, e As FileSystemEventArgs)
Try
Dim x = e.Name
List1.Add(x)
Dim path As String = e.FullPath
Dim i = InStr(path, ".")
Dim y = InStr(path, "~$")
If File.Exists(path) Then
List.Add(path)
End If
If path.EndsWith(".txt") Or path.EndsWith(".docx") Or path.EndsWith(".xlsx") Or path.EndsWith(".csv") Then
If System.IO.Directory.Exists(path) Then
LbxWatching.Items.Add(Now.ToLocalTime & " - " & path & " - " & e.ChangeType.ToString)
List.Add(path)
'My.Computer.FileSystem.CopyDirectory(TbxFrom.Text, TbxTo.Text, True)
System.IO.File.Copy(path, TbxTo.Text.ToString & "\" & e.Name, True)
End If
End If
If path.EndsWith(".txt") Or path.EndsWith(".docx") Or path.EndsWith(".xlsx") Or path.EndsWith(".csv") Then
If i > 0 And y = 0 Then
If Not path.Substring(path.Length - 4) = ".tmp" And Not path.Substring(path.Length - 4) = ".TMP" Then
LbxWatching.Items.Add(Now.ToLocalTime & " - " & path & " - " & e.ChangeType.ToString)
List.Add(path)
'My.Computer.FileSystem.CopyDirectory(TbxFrom.Text, TbxTo.Text, True)
My.Computer.FileSystem.CopyFile(path, TbxTo.Text.ToString & "\" & e.Name, True)
End If
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
List.Clear()
List1.Clear()
End Sub
Private Sub FileWatcher_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim appsettings = ConfigurationManager.AppSettings
Dim result As String
For Each result In appsettings
If result = "Key0" Then
TbxFrom.Text = appsettings("Key0")
ElseIf result = "Key1" Then
TbxTo.Text = appsettings("Key1")
End If
Next
MapDrive("X", TbxTo.Text)
Watcher = New FileSystemWatcher()
Watcher.Path = TbxFrom.Text
Watcher.Filter = "*.*"
Watcher.IncludeSubdirectories = True
Watcher.NotifyFilter = NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName
AddHandler Watcher.Changed, AddressOf Modify
AddHandler Watcher.Created, AddressOf Createee
AddHandler Watcher.Deleted, AddressOf Delete
AddHandler Watcher.Renamed, AddressOf ChangeName
Watcher.EnableRaisingEvents = True
CheckForIllegalCrossThreadCalls = False
LbxWatching.Items.Clear()
List = New ArrayList()
List1 = New ArrayList()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
This only happens when I create files in the monitoring folder, other things like editing, deleting files, or copying a bunch of files from elsewhere are not corrupted.

Classes and textbox is not a member of class generate

Hello i'm trying to move my code to difrent classes so i can keep everything organized.
What i have now:
Public Async Sub GenButton_Click(sender As Object, e As EventArgs) Handles GenButton.Click
Dim tasks As New List(Of Task)()
tasks.Add(Task.Run(AddressOf generate))
Await Task.WhenAll(tasks)
generatedlines.Text = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Generated" & Me.NumericUpDown3.Value & ".txt")
Me.generatedlines.Lines = Me.generatedlines.Lines.Distinct.ToArray
generatedlines.SaveFile(Application.StartupPath & "\Generated" & Me.NumericUpDown3.Value & ".txt", RichTextBoxStreamType.PlainText)
MessageBox.Show("lines generated in Generated" & Me.NumericUpDown3.Value & ".txt", "Task Completed!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End Sub
What i want:
Public Class Form1
Public Async Sub GenButton_Click(sender As Object, e As EventArgs) Handles GenButton.Click
//run code of class generate
end sub
end class
public class generate
Dim tasks As New List(Of Task)()
tasks.Add(Task.Run(AddressOf generate))
Await Task.WhenAll(tasks)
generatedlines.Text = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Generated" & Me.NumericUpDown3.Value & ".txt")
Me.generatedlines.Lines = Me.generatedlines.Lines.Distinct.ToArray
generatedlines.SaveFile(Application.StartupPath & "\Generated" & Me.NumericUpDown3.Value & ".txt", RichTextBoxStreamType.PlainText)
MessageBox.Show("lines generated in Generated" & Me.NumericUpDown3.Value & ".txt", "Task Completed!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
end class
I tried this before but it will give errors like "generatedlines is not a member of class generated"

How to show download progress in progressbar? Visual Basic

im so confused because this code didn't work. It downloaded the file successfully but don't report the progress to the ProgressBar. I already started Timer1 using Timer1.Start() before BackgroundWorker2.RunWorkerAsync() .
Dim size As Double
Private Sub BackgroundWorker2_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker2.DoWork
Try
Dim G As Integer = 150
Dim Increase As Boolean = True
Do Until Clicked = True
If Increase = True Then
If Not G = 255 Then
G += 1
Threading.Thread.Sleep(10)
Else
Increase = False
End If
Else
If Not G = 150 Then
G -= 1
Threading.Thread.Sleep(10)
Else
Increase = True
End If
End If
Label6.ForeColor = Color.FromArgb(0, G, 0)
Loop
Label6.Cursor = Cursors.Default
Label6.Text = "Initializing"
Label6.ForeColor = Color.Lime
MessageBox.Show("Description :" & Environment.NewLine & Description & Environment.NewLine & Environment.NewLine & "Total Size: " & Environment.NewLine & TotalSize & Environment.NewLine & Environment.NewLine & "Download Link (Global): " & Environment.NewLine & DownlaodLink, "BIOS Update Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
'WebBrowser1.Navigate(DownlaodLink)
'BackgroundWorker1.RunWorkerAsync()
ProgressBar1.Visible = True
size = TotalSize.Replace(" MBytes", "")
Me.Refresh()
Dim wc As New WebClient
wc.DownloadFileAsync(New Uri(DownlaodLink), My.Computer.FileSystem.SpecialDirectories.Desktop & "\A55BM-E BIOS " & LatestVersion.ToString.Replace(" ", "") & ".zip")
Catch ex As Exception
MsgBox(ex.Message)
End Try
And the code to show me the progress of my download
Dim cursize As Double
Dim finsize As Double
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If System.IO.File.Exists(My.Computer.FileSystem.SpecialDirectories.Desktop & "\A55BM-E BIOS " & LatestVersion.ToString.Replace(" ", "") & ".zip") Then
cursize = My.Computer.FileSystem.GetFileInfo(My.Computer.FileSystem.SpecialDirectories.Desktop & "\A55BM-E BIOS " & LatestVersion.ToString.Replace(" ", "") & ".zip").Length
finsize = cursize / size * 100
If Not ProgressBar1.Value = ProgressBar1.Maximum Then
ProgressBar1.Value = finsize
ProgressBar1.Refresh()
Else
ProgressBar1.Value = finsize
ProgressBar1.Refresh()
Timer1.Stop()
MsgBox("Finished Downloading")
End If
End If
End Sub
I can't figure out how to make this work. Can someone help me?
Finally! I made it work but didn't go with the BackgroundWorker. The code below is what I've used to make this thing work. And it's so efficient and easy to use too.
Public WithEvents downloader As WebClient
Public Sub DownloadStart()
Label6.Cursor = Cursors.Default
Label6.Text = "Initializing"
Label6.ForeColor = Color.Lime
MessageBox.Show("Description :" & Environment.NewLine & Description & Environment.NewLine & Environment.NewLine & "Total Size: " & Environment.NewLine & TotalSize & Environment.NewLine & Environment.NewLine & "Download Link (Global): " & Environment.NewLine & DownlaodLink, "BIOS Update Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
ProgressBar1.Visible = True
downloader = New WebClient
downloader.DownloadFileAsync(New Uri(DownlaodLink), My.Computer.FileSystem.SpecialDirectories.Desktop & "\A55BM-E BIOS " & LatestVersion.ToString.Replace(" ", "") & ".zip")
End Sub
Private Sub downloader_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles downloader.DownloadProgressChanged
ProgressBar1.Value = e.ProgressPercentage
End Sub
Thanks everyone for helping me!

Folder monitor that monitors md5 code in the files only crashes

I've made a program in Visual Basic 2010 that monitors a specified folder and checks the md5 code of every modified file, when the md5 code is equal to the md5 code that I specified in the code, the program should show Form2 (Form2.Show), but the program crashes instead. And if a file changes in the folder that the program is monitoring, if I eg. try to delete the file, it says that the file is used by vshost32.exe and can't be deleted until I close the program. Can someone help me with that? Here is the code:
Imports System.IO
Imports System.Diagnostics
Imports System.Text
Imports System.Security.Cryptography
Public Class Form1
Public watchfolder As FileSystemWatcher
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
watchfolder = New System.IO.FileSystemWatcher()
watchfolder.IncludeSubdirectories = True
watchfolder.Path = TextBox1.Text
watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.FileName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.Attributes
AddHandler watchfolder.Changed, AddressOf logchange
AddHandler watchfolder.Created, AddressOf logchange
AddHandler watchfolder.Deleted, AddressOf logchange
AddHandler watchfolder.Renamed, AddressOf logrename
watchfolder.EnableRaisingEvents = True
Button1.Enabled = False
Button2.Enabled = True
End Sub
Private Sub logchange(ByVal source As Object, ByVal e As _
System.IO.FileSystemEventArgs)
If System.IO.Path.GetFileName(e.FullPath).ToLower = "log.txt" Then Exit Sub
Dim msg As String = Environment.NewLine & "File " & e.FullPath & " "
Select Case e.ChangeType
Case IO.WatcherChangeTypes.Created
msg &= "has been created" + " " + "Time:" + " " + Format(TimeOfDay)
Case IO.WatcherChangeTypes.Deleted
msg &= "has been deleted" + " " + "Time:" + " " + Format(TimeOfDay)
Case IO.WatcherChangeTypes.Changed
msg &= "has been modified" + " " + "Time:" + " " + Format(TimeOfDay)
End Select
Dim writer As New IO.StreamWriter("log.txt", True)
writer.WriteLine(msg)
writer.Close()
Dim md5code As String
Dim md5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
Dim f As FileStream = New FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
f = New FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
md5.ComputeHash(f)
Dim ObjFSO As Object = CreateObject("Scripting.FileSystemObject")
Dim objFile = ObjFSO.GetFile(e.FullPath)
Dim hash As Byte() = md5.Hash
Dim buff As StringBuilder = New StringBuilder
Dim hashByte As Byte
For Each hashByte In hash
buff.Append(String.Format("{0:X1}", hashByte))
Next
md5code = buff.ToString()
If md5code = "(The md5 code that I will add later)" Then
Form2.Show()
End If
End Sub
Public Sub logrename(ByVal source As Object, ByVal e As _
System.IO.RenamedEventArgs)
Select Case e.ChangeType
Case IO.WatcherChangeTypes.Created
Exit Sub
Case IO.WatcherChangeTypes.Changed
Exit Sub
Case IO.WatcherChangeTypes.Deleted
Exit Sub
Case Else
Dim msgrn As String = Environment.NewLine & "File " + e.OldName + " "
msgrn &= "has been renamed to" + " " + e.Name + " " + "Time:" + " " + Format(TimeOfDay)
Dim writer As New IO.StreamWriter("log.txt", True)
writer.WriteLine(msgrn)
writer.Close()
End Select
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
watchfolder.EnableRaisingEvents = False
Button1.Enabled = True
Button2.Enabled = False
End Sub
End Class
Assuming a form class named Form2, your code should be:
dim frm2 As New Form2
frm2.Show
Forms are mere classes and must be instanced in order to be used. It also appears that you are not closing the filestream used to read the file and/or releasing the objects created on the file which are probably the cause of the other error.

Folder changes monitor made in Visual Basic 2010 does not write changes correctly

I've made a program in Visual Basic 2010, that monitors and write down changes in a folder eg. when a file deletes, when a file renames, when a file creates and which files, but it's a problem. I've writed the code to make a new line when another change is made, when a change is made, it writes it down to a file named log.txt, but the log only looks like "File log.txt has been modified" because the program, when it write changes to the log, it changes the log.txt to write down the log, but the strange is, it deletes everything in the document and writes "File log..txt has been modified" even if I have writed in the code to make a new line before writing. Can someone help me with this problem? Here's the code:
Imports System.IO
Imports System.Diagnostics
Public Class Form1
Public watchfolder As FileSystemWatcher
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
watchfolder = New System.IO.FileSystemWatcher()
'this is the path we want to monitor
watchfolder.Path = TextBox1.Text
'Add a list of Filter we want to specify
'make sure you use OR for each Filter as we need to
'all of those
watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.FileName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.Attributes
' add the handler to each event
AddHandler watchfolder.Changed, AddressOf logchange
AddHandler watchfolder.Created, AddressOf logchange
AddHandler watchfolder.Deleted, AddressOf logchange
' add the rename handler as the signature is different
AddHandler watchfolder.Renamed, AddressOf logrename
'Set this property to true to start watching
watchfolder.EnableRaisingEvents = True
Button1.Enabled = False
Button2.Enabled = True
'End of code for btn_start_click
End Sub
Private Sub logchange(ByVal source As Object, ByVal e As _
System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
Dim writer As New IO.StreamWriter("log.txt")
writer.WriteLine(Chr(13) & "File" + " " + e.FullPath + " " + "has been modified")
writer.Close()
End If
If e.ChangeType = IO.WatcherChangeTypes.Created Then
Dim writer As New IO.StreamWriter("log.txt")
writer.WriteLine(Chr(13) & "File" + " " + e.FullPath + " " + "has been created")
writer.Close()
End If
If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
Dim writer As New IO.StreamWriter("log.txt")
writer.WriteLine(Chr(13) & "Filde" + " " + e.FullPath + " " + "has been deleted")
writer.Close()
End If
End Sub
Public Sub logrename(ByVal source As Object, ByVal e As _
System.IO.RenamedEventArgs)
Dim writer As New IO.StreamWriter("log.txt")
writer.WriteLine(Chr(13) & "File" + " " + e.FullPath + "has been renamed to" + " " + e.Name)
writer.Close()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
' Stop watching the folder
watchfolder.EnableRaisingEvents = False
Button1.Enabled = True
Button2.Enabled = False
End Sub
End Class
When you open your streamwriter, you are not telling it to append, so it overwrites:
Dim writer As New IO.StreamWriter("log.txt", True)
Also, you dont need a new stream for each activity:
Dim msg as string= Environment.NewLine & "File " & e.FullPath & " "
Select case e.ChangeType
case IO.WatcherChangeTypes.Created
msg &= "has been created"
case IO.WatcherChangeTypes.Deleted
msg &= "has been deleted"
...etc
End Select
Dim writer As New IO.StreamWriter("log.txt", True)
writer.WriteLine(msg)
writer.Close()
..you could also leave the stream open until the watcher ends
You probably should exempt logging changes to log.txt, so test e.FullPath:
If System.Io.Path.GetFileName(e.FullPath).ToLower = "log.text" Then Exit Sub
Now the program in working! Thank you MPelletier and Plutonix for the amazing help! Here is the complete code:
Imports System.IO
Imports System.Diagnostics
Public Class Form1
Public watchfolder As FileSystemWatcher
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
watchfolder = New System.IO.FileSystemWatcher()
watchfolder.IncludeSubdirectories = True
watchfolder.Path = TextBox1.Text
watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.FileName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.Attributes
AddHandler watchfolder.Changed, AddressOf logchange
AddHandler watchfolder.Created, AddressOf logchange
AddHandler watchfolder.Deleted, AddressOf logchange
AddHandler watchfolder.Renamed, AddressOf logrename
watchfolder.EnableRaisingEvents = True
Button1.Enabled = False
Button2.Enabled = True
End Sub
Private Sub logchange(ByVal source As Object, ByVal e As _
System.IO.FileSystemEventArgs)
If System.IO.Path.GetFileName(e.FullPath).ToLower = "log.txt" Then Exit Sub
Dim msg As String = Environment.NewLine & "File " & e.FullPath & " "
Select Case e.ChangeType
Case IO.WatcherChangeTypes.Created
msg &= "has been created" + " " + "Time:" + " " + Format(TimeOfDay)
Case IO.WatcherChangeTypes.Deleted
msg &= "has been deleted" + " " + "Time:" + " " + Format(TimeOfDay)
Case IO.WatcherChangeTypes.Changed
msg &= "has been modified" + " " + "Time:" + " " + Format(TimeOfDay)
End Select
Dim writer As New IO.StreamWriter("log.txt", True)
writer.WriteLine(msg)
writer.Close()
End Sub
Public Sub logrename(ByVal source As Object, ByVal e As _
System.IO.RenamedEventArgs)
Select e.ChangeType
Case IO.WatcherChangeTypes.Created
Exit Sub
Case IO.WatcherChangeTypes.Changed
Exit Sub
Case IO.WatcherChangeTypes.Deleted
Exit Sub
Case Else
Dim msgrn As String = Environment.NewLine & "File " + e.OldName + " "
msgrn &= "has been renamed to" + " " + e.Name + " " + "Time:" + " " + Format(TimeOfDay)
Dim writer As New IO.StreamWriter("log.txt", True)
writer.WriteLine(msgrn)
writer.Close()
End Select
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
watchfolder.EnableRaisingEvents = False
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Me.Hide()
MsgBox("To close it later, don't open the program again, press CTRL+ALT+DELETE and press Start Task Manager or something like that, and go to processes and kill FolderMonitor.exe or what you have named the file", 0 + 64, "FolderMonitor")
End Sub
End Class