I've got this code:
Try
cmd.Kill()
Catch ex As Exception
End Try
TextBox2.Clear()
If TextBox1.Text.Contains(" ") Then
psi = New ProcessStartInfo(TextBox1.Text.Split(" ")(0), TextBox1.Text.Split(" ")(1))
Else
psi = New ProcessStartInfo("C:/Bukkit Runner/run.bat")
End If
Dim systemencoding As System.Text.Encoding
System.Text.Encoding.GetEncoding(Globalization.CultureInfo.CurrentUICulture.TextInfo.OEMCodePage)
With psi
.UseShellExecute = False
.RedirectStandardError = True
.RedirectStandardOutput = True
.RedirectStandardInput = True
.CreateNoWindow = True
.StandardOutputEncoding = systemencoding
.StandardErrorEncoding = systemencoding
End With
cmd = New Process With {.StartInfo = psi, .EnableRaisingEvents = True}
AddHandler cmd.ErrorDataReceived, AddressOf Async_Data_Received
AddHandler cmd.OutputDataReceived, AddressOf Async_Data_Received
cmd.Start()
cmd.BeginOutputReadLine()
cmd.BeginErrorReadLine()
And Textbox command
If TextBox1.Text.Contains(" ") Then
psi = New ProcessStartInfo(TextBox1.Text.Split(" ")(0), TextBox1.Text.Split(" ")(1))
Else
psi = New ProcessStartInfo(TextBox1.Text$)
End If
Dim systemencoding As System.Text.Encoding
System.Text.Encoding.GetEncoding(Globalization.CultureInfo.CurrentUICulture.TextInfo.OEMCodePage)
With psi
.UseShellExecute = False
.RedirectStandardError = True
.RedirectStandardOutput = True
.RedirectStandardInput = True
.CreateNoWindow = True
.StandardOutputEncoding = systemencoding
.StandardErrorEncoding = systemencoding
End With
cmd = New Process With {.StartInfo = psi, .EnableRaisingEvents = True}
AddHandler cmd.ErrorDataReceived, AddressOf Async_Data_Received
AddHandler cmd.OutputDataReceived, AddressOf Async_Data_Received
cmd.Start()
cmd.BeginOutputReadLine()
cmd.BeginErrorReadLine()
But i get this error if i do stop in the console:
http://prntscr.com/9jvf90
The first begin command works OK. http://prntscr.com/9jvfqe
What can i do to run commands in the bat file?
As a Minecrafter, I can clearly see that you are trying to run a Bukkit server.
Maybe this will help?
Private Sub MyCode(sender As Object, e As EventArgs) Handles <stuff>
Try
Try
cmd.Kill()
Catch ex As Exception
End Try
TextBox2.Clear()
Textbox_TextChanged(sender,e)
Catch
End
End Try
End Sub
Private Sub Textbox_TextChanged(sender As Object, e As EventArgs) Handles Textbox1.textChanged, Textbox2.TextChanged
Try
If TextBox1.Text.Contains(" ") Then
psi = New ProcessStartInfo(TextBox1.Text.Split(" ")(0), TextBox1.Text.Split(" ")(1))
Else
psi = New ProcessStartInfo(TextBox1.Text$)
End If
Dim systemencoding As System.Text.Encoding
System.Text.Encoding.GetEncoding(Globalization.CultureInfo.CurrentUICulture.TextInfo.OEMCodePage)
With psi
.UseShellExecute = False
.RedirectStandardError = True
.RedirectStandardOutput = True
.RedirectStandardInput = True
.CreateNoWindow = True
.StandardOutputEncoding = systemencoding
.StandardErrorEncoding = systemencoding
End With
cmd = New Process With {.StartInfo = psi, .EnableRaisingEvents = True}
AddHandler cmd.ErrorDataReceived, AddressOf Async_Data_Received
AddHandler cmd.OutputDataReceived, AddressOf Async_Data_Received
cmd.Start()
cmd.BeginOutputReadLine()
cmd.BeginErrorReadLine()
Catch
End
End Try
End Sub
Related
I've set up my filesystemwatcher, but I'm getting odd results. I've found that if I put a complete path of a directory, and set include subdirectories, then changes are channeled as they should. But what I've tried to do unsuccessfully is set my "C:\" drive as the path with include subdirectories.
Are there restrictions on using the main drive as a path?
I've tried every syntax of it I could, but no success. Just wondering if there's something there I don't know...comments welcome :)
Here's pertinent code if anyone wants to take a look at it. Suggestions would be great:
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")>
Private Sub WatchFolders()
Dim myConn As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\kgene\source\repos\Test Program\Test Program\Resources\BakDb.accdb")
MessageBox.Show("setting up watch folders")
watcher = New FileSystemWatcher With {.NotifyFilter = NotifyFilters.DirectoryName Or NotifyFilters.FileName Or NotifyFilters.Attributes}
watcher.Path = "c:\"
watcher.IncludeSubdirectories = True
watcher.EnableRaisingEvents = True
AddHandler watcher.Changed, AddressOf LogChange
AddHandler watcher.Created, AddressOf LogChange
AddHandler watcher.Deleted, AddressOf LogChange
AddHandler watcher.Renamed, AddressOf LogChangeR
End Sub
Private Sub LogChange(ByVal source As Object, ByVal e As FileSystemEventArgs)
Dim myConn As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\kgene\source\repos\Test Program\Test Program\Resources\BakDb.accdb")
Dim cmd As New OleDbCommand
chkCnt = 0
Try
str = "SELECT Base, Target FROM Backup"
cmd.Connection = myConn
cmd.CommandText = str
myConn.Open()
Dim lstReader As OleDbDataReader = cmd.ExecuteReader()
If cntPlns = 0 Then
myConn.Close()
Exit Sub
End If
lstReader.Read()
Do Until chkCnt = cntPlns
If lstReader.Item(0).ToString().ToLower() = Path.GetDirectoryName(e.FullPath).ToString.ToLower() Or lstReader.Item(1).ToString().ToLower() = Path.GetDirectoryName(e.FullPath).ToString().ToLower() Then
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
MessageBox.Show("first item changed")
End If
If e.ChangeType = IO.WatcherChangeTypes.Created Then
MessageBox.Show("first item create")
End If
If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
MessageBox.Show("first item delete")
End If
End If
If cntPlns = 0 Then
myConn.Close()
Exit Sub
End If
lstReader.Read()
chkCnt += 1
Loop
chkCnt = 0
myConn.Close()
Catch ex As Exception
chkCnt = 0
myConn.Close()
MessageBox.Show("There was a problem conncecting to the database to watch your folders")
Exit Sub
End Try
End Sub
I moved the
watcher.EnableRaisingEvents = True
after the code that register the events as Jimi suggested. This solve the problem setting up the watched folders to register events as expected.
This is to run the openfiles.exe and return the output from it
If i run openfiles.exe at the command line it works as expected
When I run it here there is no error but i get nothing in the Messagebox
Dim NewProcess As New Process()
With NewProcess.StartInfo
.FileName = "openfiles.exe"
.Arguments = "/query /s FakeServer/fo csv /V /U FakeDomain\Fakeuser/P pword"
.RedirectStandardOutput = True
.RedirectStandardError = True
.RedirectStandardInput = True
.UseShellExecute = False
.WindowStyle = ProcessWindowStyle.Normal
.CreateNoWindow = False
End With
NewProcess.Start()
System.Threading.Thread.Sleep(5000)
MsgBox(NewProcess.StandardOutput.ReadToEnd)
This is just a sample code that I have that is similar to what you are trying to do. However, my app was trying to run a command using cmd.exe and display the result in real time to a textbox. You can try to modify it accordingly.
Dim cmd As New Process()
Dim strCommandLine As String = "Echo Hello World"
cmd.StartInfo.FileName = "cmd.exe"
cmd.StartInfo.RedirectStandardError = True
cmd.StartInfo.RedirectStandardInput = True
cmd.StartInfo.RedirectStandardOutput = True
cmd.StartInfo.CreateNoWindow = True
cmd.StartInfo.UseShellExecute = False
cmd.EnableRaisingEvents = True
Application.DoEvents()
AddHandler cmd.ErrorDataReceived, AddressOf OutputHandler
AddHandler cmd.OutputDataReceived, AddressOf OutputHandler
cmd.Start()
cmd.StandardInput.WriteLine(strCommandLine)
cmd.StandardInput.Flush()
cmd.StandardInput.Close()
cmd.BeginErrorReadLine()
cmd.BeginOutputReadLine()
cmd.Close()
Delegate Sub UpdateTextBoxDelg(text As String)
Public myDelegate As UpdateTextBoxDelg = New UpdateTextBoxDelg(AddressOf UpdateTextBox)
Public Sub UpdateTextBox(text As String)
txtOutput.Text += text & Environment.NewLine
txtOutput.SelectionStart = txtOutput.Text.Length
txtOutput.ScrollToCaret()
End Sub
Private Sub OutputHandler(sender As Object, e As DataReceivedEventArgs)
If Me.InvokeRequired = True Then
Me.Invoke(myDelegate, e.Data)
Else
UpdateTextBox(e.Data)
End If
End Sub
Guys I need to convert this into WebClient in Windows Service Application.
Dim webBrowser1 As New WebBrowser
Dim pageready As Boolean = False
Dim timer As System.Diagnostics.Stopwatch = New Stopwatch
Private aTimer As System.Timers.Timer
Dim request As HttpWebRequest = Nothing
Dim webappID As String = String.Empty
Dim appName As String = String.Empty
Public Sub WaitForPageLoad()
Dim dtWebApp As Data.DataTable = BLL.fnListofWebApp()
Dim webappURL As String = String.Empty
If (dtWebApp.Rows.Count > 0) Then
For Each row As DataRow In dtWebApp.Rows
webappURL = (row.Field(Of String)("application_url"))
webappID = (row.Field(Of Integer)("web_apps_id"))
appName = (row.Field(Of String)("application_name"))
serverName = (row.Field(Of String)("server_name"))
Try
webBrowser1.Navigate("webappURL")
request = CType(System.Net.WebRequest.Create(webappURL), System.Net.HttpWebRequest)
request.CookieContainer = New System.Net.CookieContainer
request.Credentials = CredentialCache.DefaultCredentials
CType(request, HttpWebRequest).UserAgent = ".NET Framework Example Client"
timer.Start()
AddHandler webBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
While Not pageready
Application.DoEvents()
If Not SumState = "" Then
pageready = True
SavingError()
SumState = ""
End If
End While
pageready = False
Catch ex As Exception
SumState = ex.Message
End Try
Next
Else
End If
End Sub
Public Sub SavingError()
timer.Stop()
'Dim timeTaken As TimeSpan = timer.Elapsed
'Dim totalSeconds As String = timeTaken.TotalSeconds()
'Dim RoundedOff As String = (FormatNumber(CDbl(totalSeconds), 2))
'Saving to tblServer_Status
Dim server As New ServerList
Try
Dim RightNow As Date = Now
server.SiteCode = strSiteCode
server.WebAppID = webappID
server.SummaryState = "Critical"
server.LastCheck = DateTime.Now.ToString()
server.NextCheck = RightNow.AddMinutes(30)
server.Duration = 0
BLL.fnInsertWebStat(server)
Catch ex As Exception
SumState = ex.Message
End Try
timer.Reset()
RemoveHandler webBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
End Sub
Public Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
Try
If webBrowser1.ReadyState = WebBrowserReadyState.Complete Then
Dim response As WebResponse = request.GetResponse()
pageready = True
response.Close()
timer.Stop()
Dim server As New ServerList
Try
Dim RightNow As Date = Now
server.SiteCode = strSiteCode
server.WebAppID = webappID
server.SummaryState = "OK"
server.LastCheck = DateTime.Now.ToString()
server.NextCheck = RightNow.AddMinutes(30)
server.Duration = RoundedOff
BLL.fnInsertWebStat(server)
Catch ex As Exception
SumState = ex.Message
End Try
timer.Reset()
RemoveHandler webBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
End If
Catch ex As Exception
SumState = ex.Message
End Try
End Sub
Help me to configure this into WebClient. Because WebBroser doesn't work in Windows Service Application.
Help?
I badly needed this codes. please help me.
I run multiple command line processes, starting them in a loop. It works and starts all of them async.
Public Sub DoWork
Dim i As Integer = 0
While (Args_reader.Peek() > -1)
i = i + 1
MyArg = Args_reader.ReadLine
Dim MyArg As String
Dim MyProcess(i) As Process
MyProcess(i) = New Process
With MyProcess(i).StartInfo
.FileName = MyFile
.Arguments = MyArg
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
.WindowStyle = ProcessWindowStyle.Hidden
End With
MyProcess(i).Start()
End While
Args_reader.Close()
i = 0
End Sub
Haw can I read stdOutput for all of them and check their status?
I need to wait until they finish to continue executing the program.
I would recommend you to assign async events to every process inside a loop, so they get fired when that process has any output. Standard Output or Error Output:
Dim Proceso As New Process
'Add the event handlers:
AddHandler Proceso.OutputDataReceived, AddressOf CallbackProcesoAsync
AddHandler Proceso.ErrorDataReceived, AddressOf ErrorDataReceivedAsync
Dim startInfo As New ProcessStartInfo
startInfo.FileName = execFile
startInfo.RedirectStandardOutput = True
startInfo.RedirectStandardError = True
startInfo.CreateNoWindow = False
Proceso.StartInfo = startInfo
Proceso.Start()
the async events should be something like this:
Private Sub CallbackProcesoAsync(sender As Object, args As System.Diagnostics.DataReceivedEventArgs)
If Not args.Data Is Nothing AndAlso Not String.IsNullOrEmpty(args.Data) Then
'args.Data have the output
End If
End Sub
Private Sub ErrorDataReceivedAsync(sender As Object, args As System.Diagnostics.DataReceivedEventArgs)
If Not args.Data Is Nothing AndAlso Not String.IsNullOrEmpty(args.Data) Then
'args.Data have the output
End If
End Sub
I'm trying to redirect the output from a command-line application in VB.NET, and for some reason it fails to redirect the output. Here's my code:
Dim myProcess As Process = New Process
myProcess.StartInfo.FileName = "g++"
myProcess.StartInfo.Arguments = CMDLineCommand
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
Dim output As String = myProcess.StandardOutput.ReadToEnd
myProcess.WaitForExit()
CMDLineOutputTextBox.Text = output
Does anybody know why it's not being redirected? Thanks in advance!
-Neil
EDIT: Here's my full code, in case there's anything weird with my syntax:
Dim myProcess As Process = New Process
myProcess.StartInfo.FileName = "g++"
myProcess.StartInfo.Arguments = CMDLineCommand
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.EnableRaisingEvents = True
AddHandler myProcess.OutputDataReceived, AddressOf GotData
myProcess.Start()
CMDLineOutputTextBox.Text = ""
myProcess.BeginOutputReadLine()
Later on...
Private Sub GotData(sendingProcess As Object, outLine As DataReceivedEventArgs)
If Not String.IsNullOrEmpty(outLine.Data) Then
SetText(outLine.Data)
End If
End Sub
Delegate Sub SetTextCallback(value As String)
Private Sub SetText(ByVal value As String)
If Me.CMDLineOutputTextBox.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {value})
Else
Me.CMDLineOutputTextBox.Text += value + Environment.NewLine
End If
End Sub
Anything weird?
Your method will work, provided by the time you hit the line where you read the output to the end, all of the output is there. Since you are using g++, I assume that may not always be the case. You will probably be better off using the OutputDataReceived Event and capturing the data from that.
Dim myProcess As Process = New Process
myProcess.StartInfo.FileName = "ping"
myProcess.StartInfo.Arguments = "www.google.com"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.EnableRaisingEvents = True
AddHandler myProcess.OutputDataReceived, AddressOf GotData
myProcess.Start()
myProcess.BeginOutputReadLine()
Then you handle the event like this:
Private Sub GotData(sendingProcess As Object, outLine As DataReceivedEventArgs)
If Not String.IsNullOrEmpty(outLine.Data) Then
SetText(outLine.Data)
End If
End Sub
Delegate Sub SetTextCallback(value As String)
Private Sub SetText(ByVal value As String)
If Me.TextBox3.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {value})
Else
Me.TextBox3.Text += value + Environment.NewLine
End If
End Sub
I have noticed the waitforExit seems to make the code lock during the invoke.required check. When I take out the waitforexit it works.