standard outputread does not read anything until process is closed vb.net - vb.net

I am trying to redirect the output from xfoil.exe with downloadables here. The issue is when I am redirecting the standardoutput, my code will not read anything until I use the "quit" command which closes the external xfoil.exe and hence, I cannot run any further commands.
first defining variables
Dim p as process = New Process()
Dim startinfo = New ProcessStartInfo()
Dim bt As Threading.Thread
I start the process using
With startinfo
.FileName = Application.StartupPath & "\appdata\xfoil.exe"
.Arguments = ""
.WorkingDirectory = Application.StartupPath
.RedirectStandardError = True
.RedirectStandardOutput = True
.RedirectStandardInput = True
.UseShellExecute = False
.CreateNoWindow = True
End With
p.StartInfo = startinfo
p.EnableRaisingEvents = True
If Not IsNothing(bt) Then bt.Abort()
bt = New Threading.Thread(AddressOf ReadThread)
bt.IsBackground = True
bt.Start()
p.Start()
The definition for the ReadThread is
Private Sub ReadThread()
Dim rLine As String
Do Until Leaving
Try
rLine = p.StandardOutput.Read()
logtext += (Chr(rLine))
If p.StandardOutput.Peek = -1 Then
Me.Invoke(Sub() txtLog.AppendText(logtext))
logtext = ""
End If
Catch ex As Exception
Console.WriteLine("error " & ex.Message)
End Try
Loop
End Sub
This setup works perfectly with another app from the same developer Mark Drela. When I use the other app AVL with download link here everything works fine. However, xfoil does not work with this setup and I have spent some hours on this without any luck. I am using VB.net on Windows 10 in Visual Studio.NET 2019 community edition.
Edit
Both methods using threading and events were implemented and no luck.
A sample code using both methods in VB.net is now available on Github for review comments. Let me know if anyone has any experience with this and can help. This would really help my students in the class!

Related

The process tried to write to a nonexistent pipe vb.net

I'm currently writing a sub in vb.net that is supposed to create and/or erase tasks in the task scheduler that comes with windows 10. The creation part works fine, but when I try to erase the task I get this error in the visual studio console: "The process tried to write to a nonexistent pipe", and the task is (of course) still there. I've looked for a solution but can't find anything similar. Here is the code:
Private Sub SimpleButton2_Click(sender As Object, e As EventArgs) Handles sbAutoRun.Click
Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
CMDThread.Start()
End Sub
Private Sub CMDAutomate()
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo
Dim sTime As String = teAutoRun.Time.ToString("HH:mm")
Dim sCmdCommand As String = "SCHTASKS /CREATE /SC DAILY /TN ""MyTasks\task"" /TR ""'" & My.Application.Info.DirectoryPath & "\program.exe' Auto"" /ST " & sTime & " /RL HIGHEST"
Dim sCmdCommand2 As String = "SCHTASKS /DELETE /TN ""MyTasks\task"""
My.Settings.AutoRun = ceAutoRun.Checked
StartInfo.FileName = "cmd" 'starts cmd window
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.CreateNoWindow = True '<---- if you want to not create a window
StartInfo.UseShellExecute = False 'required to redirect
myprocess.StartInfo = StartInfo
myprocess.Start()
Dim SR As System.IO.StreamReader = myprocess.StandardOutput
Dim SW As System.IO.StreamWriter = myprocess.StandardInput
If My.Settings.AutoRun And Not My.Settings.AutoRunExists Then
SW.WriteLine(sCmdCommand)
My.Settings.AutoRunExists = True
Console.WriteLine(sCmdCommand)
ElseIf My.Settings.AutoRun And My.Settings.AutoRunExists Then
SW.WriteLine(sCmdCommand2)
SW.WriteLine("y")
SW.WriteLine(sCmdCommand)
Else
SW.WriteLine(sCmdCommand2)
SW.WriteLine("y")
My.Settings.AutoRunExists = False
Console.WriteLine(sCmdCommand2)
End If
SW.WriteLine("exit") 'exits command prompt window
SW.Close()
SR.Close()
My.Settings.Save()
End Sub
Thanks..
Ps: The commands work fine when entered by hand in the cmd.
Update: Changed this
sCmdCommand2 As String = "SCHTASKS /DELETE /TN ""MyTasks\task"""
SW.WriteLine(sCmdCommand2)
SW.WriteLine("y")
and wrote it like this
sCmdCommand2 As String = "SCHTASKS /DELETE /TN ""MyTasks\task"" /F"
SW.WriteLine(sCmdCommand2)
Now it works fine.

Process.Start() with "manage-bde.exe" crashing in VB.NET

I'm trying to start manage-bde.exe as a new process in VB.net but when it tries to start the proc, Bitlocker crashes. Could anyone please tell me what I'm doing wrong here? This code was converted from C# where it works all day long....
Code:
Private Sub btnLock_Click(sender As Object, e As EventArgs) Handles btnLock.Click
Dim drvSelected As String = cmbDriveSelect.SelectedValue.ToString()
Dim sysDirWithBDE As String = Environment.SystemDirectory + "\manage-bde.exe"
Dim lockStatus As String = String.Empty
' This is the code for the base process
Dim myProcess As New Process()
' Start a new instance of this program
Dim myProcessStartInfo As New ProcessStartInfo(sysDirWithBDE, " -lock " + drvSelected.Remove(2))
'Set Use Shell to false so as to redirect process run info to application
myProcessStartInfo.UseShellExecute = False
myProcessStartInfo.RedirectStandardOutput = True
myProcess.StartInfo = myProcessStartInfo
Try
myProcess.Start()
lblDriveLockMsg.Show()
Catch err As Exception
lblDriveLockMsg.Text = err.Message
End Try
'Read the standard output of the process.
lockStatus = myProcess.StandardOutput.ReadToEnd()
If lockStatus.Contains("code 0x80070057") Then
lblDriveLockMsg.Text = "Drive selected is not Bit Locker encrypted"
ElseIf lockStatus.Contains("code 0x80070005") Then
lblDriveLockMsg.Text = "Drive selected is in use by an application on your machine, force dismounting might result in data loss, please check and close any applications using the drive"
Else
lblDriveLockMsg.Text = lockStatus
End If
myProcess.WaitForExit()
myProcess.Close()
End Sub

Using cmd in VB, using commands and receiving output

I need to know, if you could help me, how to insert commands in vb then they run in cmd and i get the output.
I need to do "net localgroup Administradores a58465 /add" and get the error message if there is one.
Solution: `Dim myProcess As Process = New Process
Dim s As String
myProcess.StartInfo.FileName = "c:\windows\system32\cmd.exe"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.CreateNoWindow = True
myProcess.StartInfo.RedirectStandardInput = True
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.Start()
Dim sIn As System.IO.StreamWriter = myProcess.StandardInput
Dim sOut As System.IO.StreamReader = myProcess.StandardOutput
Dim sErr As System.IO.StreamReader = myProcess.StandardError
'sIn.AutoFlush = True
sIn.Write("cls" & System.Environment.NewLine)
sIn.Write("net user" & System.Environment.NewLine)
sIn.Write("exit" & System.Environment.NewLine)
s = sOut.ReadToEnd()
If Not myProcess.HasExited Then
myProcess.Kill()
End If
LB1.Text = s
LB1.Visible = True
sIn.Close()
sOut.Close()
sErr.Close()
myProcess.Close()`
Check out Process.Start. http://msdn.microsoft.com/en-us/library/0w4h05yb(v=vs.110).aspx
Also look for the ProcessStartInfo class, which will give you options on how to kick off an external process.
Console input and output can be made available to your program through ProcessStartInfo.

How to start a visible process

I have the following code to start the program R (even though I think that the program is not relevent for the problem here) and run a script:
Public Shared Sub RunRScript(rCodeFilePath As String, rScriptExecutablePath As String, args As String)
Dim file As String = rCodeFilePath
Dim result As String = String.Empty
Try
Dim info = New ProcessStartInfo()
info.FileName = rScriptExecutablePath
info.WorkingDirectory = Path.GetDirectoryName(rScriptExecutablePath)
info.Arguments = rCodeFilePath & " " & args
info.RedirectStandardInput = False
info.RedirectStandardOutput = True
info.UseShellExecute = False
info.CreateNoWindow = True
Using proc = New Process()
proc.StartInfo = info
proc.Start()
result = proc.StandardOutput.ReadToEnd()
proc.Close()
End Using
Catch ex As Exception
Throw New Exception("R Script failed: " & result, ex)
End Try
End Sub
Problem is, if there is an error in the script I run within R I dont get an error message because the instance is invisible. I tried to make it visible with
.WindowStyle = ProcessWindowStyle.Normal
in all combinations of .UseShellExcecute and .CreateNoWindow but this is not working. Could anyone help me to can make my process visible?
Since you are redirecting StandardInput and StandardOutput, you should now redirect StandardError to trap the errors also.
More info available on MSDN

Wait for batch file to close before continuing - VB.net

I'm trying to run a batch file via VB and I need to wait for it to complete/exit before progressing. The issue I believe I am having is that when a batch file is executed, it opens cmd.exe and not the batch file.
This is what I am executing with VB
My.Computer.FileSystem.DeleteFile(My.Application.Info.DirectoryPath & "\PingCheck\machines.txt")
FileCopy(My.Application.Info.DirectoryPath & "\machines.txt", My.Application.Info.DirectoryPath & "\PingCheck\machines.txt")
Dim psi As New ProcessStartInfo(My.Application.Info.DirectoryPath & "\PingCheck\go.bat")
psi.RedirectStandardError = True
psi.RedirectStandardOutput = True
psi.CreateNoWindow = False
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.UseShellExecute = False
Dim process As Process = process.Start(psi)
process.WaitForExit()
ProgressBar1.Value = ProgressBar1.Value + 2
FileCopy(My.Application.Info.DirectoryPath & "\PingCheck\machines.txt", My.Application.Info.DirectoryPath & "\machines.txt")
'My.Computer.FileSystem.DeleteFile(My.Application.Info.DirectoryPath & "\ping.bat")
MsgBox("Ping Check Complete")
The problem im having is that it will just delete ping.bat before it completes.
How do I go about monitoring the process from the batch file I call. Then once it exits, continue with the script?
RHicke shows a nice example of how to run a batch process in VB.NET here, Run batch file in vb.net?.
To expand, you should use the function WaitForExit() to wait for the process to complete.
Dim psi As New ProcessStartInfo("Path TO Batch File")
psi.RedirectStandardError = True
psi.RedirectStandardOutput = True
psi.CreateNoWindow = False
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.UseShellExecute = False
Dim process As Process = Process.Start(psi)
process.WaitForExit()
You could use the System.Diagnostics.Process class to start the batch file. The process reference will give you access to the property HasExited (and more interesting information). The HasExited property indicates whether a process has completed.
var process = System.Diagnostics.Process.Start(new ProcessStartInfo
{
FileName = "batch file path",
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
Arguments = "parameters if applicable",
CreateNoWindow = true
});
while(!process.HasExited)
{
// obviously do some clever here to wait
}
Code is in C# but the principle should work in VB.NET
I've done something similar before. This code invokes RoboCopy from within VB.Net, using the System.Diagnostics.Process (mentioned by rivethead_).
Dim proc As System.Diagnostics.Process = New System.Diagnostics.Process()
proc.EnableRaisingEvents = False
proc.StartInfo.FileName = "d:\robocopy\robocopy"
proc.StartInfo.Arguments = strSrcDir & " " & strDestDir & " " & strFile & " " & My.Settings.robocopyFlags
proc.Start()
proc.WaitForExit()
Otherwise, what is the ping.bat doing? Is it just doing a "ping" command? If so, maybe you could invoke that with a System.Diagnostics.Process (instead of invoking a .bat file to do it). That might give you some more control over your process.