vb.net process start & stop - vb.net

How can I create a process out of the below code so that I can tell when it starts & finishes?
Thanks in advance :)
Public Shared Function EmptyDirectory(ByVal mydir As String)
Try
'delete all directories
Dim myFolder As String
For Each myFolder In Directory.GetDirectories(mydir)
Directory.Delete(myFolder, True)
Next
'delete all files
Dim myFile As String
For Each myFile In Directory.GetFiles(mydir)
File.Delete(myFile)
Next
Catch Ex As Exception
'MsgBox(ex.Message)
End Try
Return False
End Function
FYI: This is what I thought would work:
Dim myProcess As System.Diagnostics.Process = New System.Diagnostics.Process()
myProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden
myProcess.Start(EmptyDirectory(DestDir))
Dim ClearDirectoryStartDateTime As String = DateTime.Now.ToString("d") & " " & DateTime.Now.ToString("HH:mm:ss")
StatusBoxName.Items.Add(ClearDirectoryStartDateTime & " - Cleaning")
' Wait until it ends.
myProcess.WaitForExit()
' Close the process to free resources.
myProcess.Close()

You might want to use threading. There's an interesting article on MSDN: http://msdn.microsoft.com/en-us/library/aa289178(v=vs.71).aspx

Related

Visual Basic, Capture output from cmd

Sorry if it's asked before, I found out other Solutions too complicated for me..
Anyway, i am trying to search an image via cmd in visual basic code, and save the image path to string, but i cant seem to capture the output from cmd right.
Any help will be appreciated, thanks!.
Code:
Dim imageLocation As String
Dim cmd As New Process
Dim SR As System.IO.StreamReader
cmd.StartInfo.FileName = "cmd.exe"
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
cmd.StartInfo.Arguments = "/C dir /b/s Roey.png"
cmd.Start()
SR = cmd.StandardOutput
imageLocation = SR.ReadLine
UPDATED So i found out saving the output to txt file and then read it can be more simple, so i wrote the following code:
Dim cmd As New Process
cmd.StartInfo.FileName = "cmd.exe"
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
cmd.StartInfo.Arguments = "/C dir /b/s Roey.png >
C:\Users\ירין\Desktop\Roeyyy\path.txt"
cmd.Start()
cmd.WaitForExit()
when i run the
"dir /b/s Roey.png >
C:\Users\ירין\Desktop\Roeyyy\path.txt"
on CMD it wors perfectly, so why isnt it working here? :(
I found this:
Dim MyFilePath As String = Directory.GetFiles([SomePath], "*.png", SearchOption.AllDirectories).
Where(Function(f) f.Contains("Roey.png")).FirstOrDefault()
Solved!
You are a programmer so you search for files.
Imports System.Runtime.InteropServices
Sub Main
'On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Dirname = InputBox("Enter Dir name")
ProcessFolder DirName
End Sub
Sub ProcessFolder(FolderPath)
On Error Resume Next
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
msgbox Thing.Name & " " & Thing.path
'fso.copyfile thing.path, "C:\backup"
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
ProcessFolder thing.path
Next
End Sub

Vb.net problems download

How can I do a check that first download something and only after that it starts up the program.exe?
I already tried to do something like this but it excutes the file when the download is not finished and it throws some errors.
my Code:
Dim client As WebClient = New WebClient
Dim SourcePath As String = "C:\ProgramData\KDetector\UserAssistView.exe"
Dim SaveDirectory As String = "C:\ProgramData\KDetector"
Dim FileName As String = System.IO.Path.GetFileName(SourcePath)
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, FileName)
If System.IO.File.Exists(SavePath) Then
Process.Start("C:\ProgramData\KDetector\UserAssistView.exe")
Else
client.DownloadFileAsync(New Uri("http://ge.tt/70n8YPr2"), "C:\ProgramData\KDetector\")
Process.Start("C:\ProgramData\KDetector\UserAssistView.exe")
End If
You are calling the asynchronous DownloadFile method. Asynchronous method will not block the calling thread.
In order to avoid the problem, your code must be like this:
Dim downloadLink As String = "http://www.nirsoft.net/utils/userassistview.zip"
Dim saveFilePath As String = "C:\ProgramData\KDetector\userassistvkew.zip"
Dim fileName As String = Path.GetFileNameWithoutExtension(saveFilePath)
Dim client As WebClient = New WebClient
Try
CheckExsist(saveFilePath, fileName)
'Before was client.DownloadFileAsync(New Uri("http://ge.tt/70n8YPr2"))
client.DownloadFile(downloadLink, saveFilePath)
MsgBox("Download file completed. File saved in: " & saveFilePath)
'Zip extraction stuff
Catch ex As Exception
MsgBox(ex.Message)
End Try
This is the CheckExsist sub:
Private Sub CheckExsist(ByRef sourcePath As String, ByVal fileName As String, Optional ByVal counter As Integer = 1)
If System.IO.File.Exists(sourcePath) Then
sourcePath = sourcePath.Replace(Path.GetFileName(sourcePath), "") & fileName & "(" & counter & ")" & Path.GetExtension(sourcePath)
counter += 1
CheckExsist(sourcePath, fileName, counter)
End If
End Sub
I manage to download the software (from the official website) and save it as a .zip. Code the last few rows to programmatically extract the .zip, if you ecounter any problem or bug feel free to ask with another question. Anyways there are alot of post on SO regarding zip extraction on vb.net

Strange behavior when Looping through Files

This is driving us crazy, this should work!
When ran (Stepping)
It jumps over the debug.print (No Errors)
Then it hits i += 1
Never stops at the next (break point)
But i=51 !
Any Clues
If CheckBox8.Checked = False Then
Exit Function
Else
Dim fInfo As FileInfo()
Dim i As Integer = 0
Dim dInfo As DirectoryInfo = New DirectoryInfo(spath.ToString)
fInfo = dInfo.GetFiles("*.xml")
Dim sfiles As String()
Dim sFile As String
sfiles = Directory.GetFiles(spath, "*.xml")
For Each sFile In sfiles
Try
Debug.Print(sFile.ToString)
i += 1
Catch ex As Exception
Debug.Print(ex.Message)
End Try
Next
End If
This code appears to work correctly
Imports System.IO
Module Module1
Sub Main()
Dim spath As String
spath = "C:\YOUR_DIRECTORY"
Dim fInfo As FileInfo()
Dim i As Integer = 0
Dim dInfo As DirectoryInfo = New DirectoryInfo(spath.ToString)
Try
fInfo = dInfo.GetFiles("*.xml")
For Each fi In dInfo.GetFiles("*.xml")
Dim file_name As String
file_name = fi.Name
Console.WriteLine(file_name)
i = i + 1
Next
Console.WriteLine("Found:" + i.ToString + " Files")
Catch ex As Exception
Console.Write(ex.Message)
End Try
End Sub
End Module
Note: Debug.Print will print to the "Output Window" in Visual Studio, Not the command line, so..... the Debug.Print statements might not be entirely obvious if you dont have the output window open.

Killing Two different Processes With VB

I am trying to figure out how to kill two processes at the same time I have managed to get one to work when it is opened but the other wont close.
Sub block()
For Each item As Process In Process.GetProcesses
If item.ProcessName = "taskmgr" And item.ProcessName = "cmd" Then
item.Kill()
End If
Next
End Sub
As noted by #Noodles and #Zaggler your logic is wrong on this line;
If item.ProcessName = "taskmgr" And item.ProcessName = "cmd" Then
This line essentially asks if the process name is "taskmgr" and if the same process name is "cmd". Since these two strings aren't the same "taskmgr" /= "cmd" this if clause will never be true. I suggest you do something like this;
Sub block()
For Each item As Process In Process.GetProcesses
If item.ProcessName = "taskmgr" Then
item.Kill()
ElseIf item.ProcessName = "cmd" Then
item.Kill()
End If
Next
End Sub
Or optionally if you plan to close many processes;
'declare at form loading or elsewhere
Dim proclist as new list (of string)
proclist.add("taskmgr")
proclist.add("cmd")
proclist.add("...")
Sub block()
For Each item As Process In Process.GetProcesses
If proclist.contains(item.ProcessName) Then
item.Kill()
End If
Next
End Sub
Give a try with this solution in vbscript :
Option Explicit
Dim Ws,fso,MainArray,LogFile,i,OutPut,count
Set Ws = CreateObject("Wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
MainArray = Array("taskmgr.exe","cmd.exe")
LogFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "log"
count = 0
If fso.FileExists(LogFile) Then fso.DeleteFile LogFile
Set OutPut = fso.OpenTextFile(LogFile,2,True)
For i = LBound(MainArray) To UBound(MainArray)
Call Kill(MainArray(i))
Next
OutPut.WriteLine String(50,"*")
OutPut.WriteLine count & " Process were killed !"
OutPut.WriteLine String(50,"*")
If fso.FileExists(LogFile) Then
ws.run DblQuote(LogFile) 'To show the LogFile
End if
'******************************************
Sub Kill(MyProcess)
Dim colItems,objItem
Set colItems = GetObject("winmgmts:").ExecQuery("Select * from Win32_Process " _
& "Where Name like '%"& MyProcess &"%' AND NOT commandline like '%" & wsh.scriptname & "%'",,48)
For Each objItem in colItems
count= count + 1
OutPut.WriteLine Mid(objItem.CommandLine,InStr(objItem.CommandLine,""" """) + 2)
objItem.Terminate(0)
Next
End Sub
'***********************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'***********************************************

change extension and move file, using vb.net

I have the following code, which changes the extension of a txt to doc, and then moves it (from d:\1 to d:\2). The extension changes successfully, but it does not move, and I get an error
Cannot create a file when that file already exists.
Please suggest.
For Each filePath In Directory.GetFiles("D:\1", "*.txt")
File.Move(filePath, Path.ChangeExtension(filePath, ".doc"))
Next
Dim filesToMove = From f In New DirectoryInfo("d:\1").EnumerateFiles("*.doc")
For Each f In filesToMove
f.MoveTo("d:\2")
Next
This will check for an existing file of the same name and delete it first (you may want to handle this differently). It will then move and rename in one call to File.Move
Dim directory1 = "D:\1"
Dim directory2 = "D:\2"
For Each oldFileName In Directory.GetFiles(directory1, "*.txt")
Dim newFileName = Path.ChangeExtension(oldFileName, ".doc").Replace(directory1, directory2)
If File.Exists(newFileName) Then File.Delete(newFileName)
File.Move(oldFileName, newFileName)
Next
ok, finally found the solution. not very professional, but works anyways: ( Many thanks to all members who have helped earlier)
Private Sub logchange(ByVal source As Object,
ByVal e As System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
Dim sourceDirectory As String = "D:\1"
Dim archiveDirectory As String = "D:\2"
Try
Dim jpgFiles = Directory.EnumerateFiles(sourceDirectory, "*.wav")
For Each currentFile As String In jpgFiles
Dim fileName = Path.GetFileName(currentFile)
Directory.Move(currentFile, Path.Combine(archiveDirectory,
Path.GetFileNameWithoutExtension(fileName) & ".doc"))
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End If
If e.ChangeType = IO.WatcherChangeTypes.Created Then
Dim sourceDirectory As String = "D:\1"
Dim archiveDirectory As String = "D:\2"
Try
Dim jpgFiles = Directory.EnumerateFiles(sourceDirectory, "*.wav")
For Each currentFile As String In jpgFiles
Dim fileName = Path.GetFileName(currentFile)
Directory.Move(currentFile, Path.Combine(archiveDirectory,
Path.GetFileNameWithoutExtension(fileName) & ".doc"))
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End If
End Sub