Different results for exit conditions in process call - vb.net

As a small part of a project, I'm calling ffmpeg to convert a video - I worked from an old example that used some of the output to create a progress bar, which was hanging. Code below:
[initiation code common to both examples]
Dim inputFile, outputFile As String, myProcess As New Process
Dim psiProcInfo As New ProcessStartInfo, ffreader As StreamReader
inputFile = "C:\Users\mklefass\Downloads\Video 2017-08-16 21.01.39.mov"
outputFile = "C:\Users\mklefass\Downloads\tmp2\Output"
psiProcInfo.FileName = Application.StartupPath + "\ffmpeg.exe" 'Location Of FFMPEG.EXE
psiProcInfo.Arguments = " -i " & Chr(34) & inputFile & Chr(34) & " -vf fps=5 " & Chr(34) & outputFile & "%d.jpg" & Chr(34) 'start ffmpeg with command strFFCMD string
psiProcInfo.UseShellExecute = False 'use the shell execute command we always want no
psiProcInfo.WindowStyle = ProcessWindowStyle.Hidden 'hide the ffmpeg process window
psiProcInfo.RedirectStandardError = True 'Redirect the error out so we can read it
psiProcInfo.RedirectStandardOutput = True 'Redirect the standard out so we can read it
psiProcInfo.CreateNoWindow = True
[bit that changes]
myProcess.Start()
ffreader = myProcess.StandardError
Do
Try
If Not myProcess.HasExited Then
'Debug.WriteLine(ffreader.ReadLine)
End If
Catch
If Not myProcess.HasExited Then
MsgBox("Something went wrong")
End If
End Try
Loop Until myProcess.HasExited
MsgBox("done")
I then found another example that just called the executable and then continued when it was done - as below:
[same initialisation]
Debug.WriteLine("Starting...")
myProcess.Start()
strOutput = myProcess.StandardError.ReadToEnd
myProcess.WaitForExit()
myProcess.Close()
Debug.Write(strOutput)
MsgBox("done")
The second approach worked perfectly... What's different about the "exit state" that Process.HasExited and Process.WaitForExit look for?

Related

Workaround mutually exclusive "UseShellExecute" and "RedirectStandardOutput"

I need a workaround that will have the same effect as using True on both of the mutually exclusive UseShellExecute and RedirectStandardOutput.
The reason I need this is because I want to execute my perl script as I would through a CMD.exe:
perl perlcompare.pl <file1> <file2> <file3>
Noting that putting "perl" in front there seems to be optional as the file is already a .pl file.
I would like to have access to output the run gives me, as there might be error messages that are important to the user (e.g. missing files). Is there another way to achieve this?
Dim myProcess As New System.Diagnostics.Process
myProcess.StartInfo.WorkingDirectory = "K:\Engineering\Temp\perl"
myProcess.StartInfo.UseShellExecute = True
myProcess.StartInfo.FileName = "perlcompare.pl"
myProcess.StartInfo.Arguments = """" & MasterFile & """" & " " & """" & MasterOutput & """" & " " & """" & ComparisonsOutput & """"
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.Start()
Dim sOutput As String
Using ProcessStreamReader As System.IO.StreamReader = myProcess.StandardOutput
sOutput = ProcessStreamReader.ReadToEnd()
End Using
MessageBox.Show(sOutput) 'txtOutput being the output textbox.
Quite new to the language and learning, so I will hound any clues you have for me.
I don't see why you want to set UseShellExecute to true. It needs to be false to allow redirection of the standard IO channels
If the location of the perl compiler executable is in PATH then you can just set FileName to perl. It's also better to use String.Format to build strings out of variables rather than use all those escaped quotes and concatenations
Dim myProcess As New System.Diagnostics.Process
myProcess.StartInfo.WorkingDirectory = "K:\Engineering\Temp\perl"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.FileName = "perl"
myProcess.StartInfo.Arguments = String.Format(
"perlcompare.pl ""{0}"" ""{1}"" ""{2}""",
MasterFile,
MasterOutput,
ComparisonsOutput)
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.Start()
If the location of the perl compiler isn't in the PATH then you can just put a fully-qualified file path into FileName

Batch start with parameters Error

I'm trying to make only a small program which includes the two steps decompile and start from a .java file. I can't run the .bat file correctly because DOS doesn't accept the spaces like I want.
Here's my code:
Process.Start("cmd.exe", "/c start "" """ & TextBoxJavacPath.Text & _
"""" & " " & """" & TextBoxFile.Text & """")
That's the string that comes out: (it's right)
/c "C:\Program Files\Java\jdk1.8.0_60\bin\javac.exe"
"C:\Users\Niklas\Desktop\Java\Kap06\src\eingabe\LetsReadLine.java"
If I enter it by typing in console it works, but via vb.net it doesn't work.
The error is the following: The command "C:/Program" is written incorrect or couldn't be found.
Try using this code (I don't know if it'll work) :
Private Sub Start(javacPath As String, file As String)
Using p As New Process With {
.StartInfo = New ProcessStartInfo With {
.WorkingDirectory = Path.GetDirectoryName(javacPath),
.Arguments = "/c """ & Path.GetFileName(javacPath) & """ """ & file,
.FileName = "cmd",
.CreateNoWindow = True}}
p.Start()
End Using
End Sub
And call the method like this :
Start(TextBoxJavacPath.Text, TextBoxFile.Text)
I can't test the code, because I don't have any .java file...

& operator string error with string of arguments to processStartInfo

I need to pass a string into the ProcessStartInfo for ffmpeg so that I can call the dim.Argument and have it append the strings and variables from code as I parse through the files.
I have the current filename.mp3 that the code sees in movedFileInfo but it won't allow me to append it to the string using & operators... help?
I know there may be one other way to do this utilizing the ffmpeg command in separate function to simply loop through a directory using "for" but I've not found a successful command for running my ffmpeg.exe nor the ffprompt in windows. I also need to append a carriage return when I write to merge.txt but can't find an example... I'm new to vba.
These commands work but vba is complaining about the & operator in my string with the error The operator '&' is not defined for types 'String' and 'System.IO.FileInfo'.
So what I understand is that the string I'm passing into psi.Arguments doesn't like the fact that I'm sending it a string and a variable appended using the & operator... do I simply use a comma or how do I append the variable movedFileInfo to ffmpeg -i? psi is defined above as ProcessStartInfo... so I'm not sure what types vb recognizes for it... I haven't found info on ProcessStartInfo to kick off my ffmpeg exe.
See code below:
Imports System
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
'videos are from SD card always on I:\Private\AVCHD\BDMV\STREAM\
'store files to RAID drives in folders structured as :
' F:\BUILD\FLIGHT#\CAM#\<TAIL_NUMBER>_FLT_<FLT_NUMBER>_UTC_<START_UTC_TIME>_CAM_<CAM_NUMBER>.MTS
'set base dir as directory F:\
Dim dir As String = "C:\"
Dim video_card_dir As String = "C:\1bak\" '"I:\Private\AVCHD\BDMV\STREAM\"
Directory.SetCurrentDirectory(dir)
Dim new_flightnum_directory = dir & Me.BUILD.Text & "\" & FLT.Text & "\"
'establish new video dir> F: \ BUILD \ FLIGHT # \ CAM # \
Dim new_video_directory = dir & Me.BUILD.Text & "\" & FLT.Text & "\" & Me.CAM.Text & "\"
'establish new filename to rename the video file
' TAIL # FLT #
Dim new_filename As String = TAIL.Text & "_" & FLT.Text & "_" & UTC.Text & "_" & CAM.Text
Dim ffmpeg As String = "C:\ffmpeg\bin\ffmpeg.exe"
'****FFMPEG required variables
Dim psi As ProcessStartInfo = New ProcessStartInfo("C:\ffmpeg\bin\ffmpeg.exe")
Dim proc As Process = Process.Start(psi)
psi.UseShellExecute = True
psi.CreateNoWindow = True
'****end FFMPEG required variables
'!!!!!!!!!!!!!!!!!!!!!!!!!!!need to add the processing below to the IF statement aboev so that if the folders exist, the video processing doesn't attempt to run on existing files
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~START - MOVE THIS DOWN BELOW CREATION OF FILE STRUCTURE WHEN DOEN DEBUGGING************
'***START MOVING the files from the card to the new directory****
For Each foundFile As String In My.Computer.FileSystem.GetFiles(video_card_dir, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.MTS")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.MoveFile(foundFile, new_video_directory & foundFileInfo.Name)
Next
For Each foundFile As String In My.Computer.FileSystem.GetFiles(video_card_dir, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.MTS")
Dim movedFileInfo As New System.IO.FileInfo(foundFile)
psi.Arguments = "ffmpeg -i " & movedFileInfo & " -vcodec -c libx264 " & movedFileInfo & ".mp4"
psi.ToString()
'proc = Process.Start(psi)
'***convert each MTS file in the new directory to MP4****
'Writes filenames to merge.txt as " path\to\merge.txt , 'file ' F:\path\to\ file1 .MP4 '" so that ffmpeg can merge, then rename
'My.Computer.FileSystem.WriteAllText(new_video_directory & "merge.txt", "file '" & movedFileInfo & ".mp4'" & vbCrLf, True)
'>>>>need to add carriage return to text file
'NOW CAPTURE FILENAMES OF MP4 and MERGE INTO 1 MP4 FILE
' merge all F:\path\to\merge.txt to merge the files & merge them
'psi.Arguments = "ffmpeg -f concat -i " & new_video_directory & "merge.txt -c copy " & new_filename & ".mp4"
proc = Process.Start(psi)
Next
'***END MERGE FILES***
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~* END - MOVE
'***START CREATE STORAGE DIRECTORY STRUCTURE ***
'Verify if the build # directory exists?
If My.Computer.FileSystem.DirectoryExists(dir & Me.BUILD.Text) Then
MessageBox.Show("The build directory exists, moving on to create subdirectories")
Else
Try
'create the new directory F:\ build \ FLIGHT #
My.Computer.FileSystem.CreateDirectory(dir & Me.BUILD.Text)
MessageBox.Show("The build directory" & dir & Me.BUILD.Text & " was created.")
Catch ex As Exception
MessageBox.Show("Doh! The build directory could not be created! Error: " & ex.Message, "Error creating directory.", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
'verify if the flight num directory exists - or create it
If My.Computer.FileSystem.DirectoryExists(new_flightnum_directory) Then
MessageBox.Show("The flight # folder already exists! Check that you have the right Flight #.")
Else
Try
'create the new directory F:\ BUILD \ FLIGHT #
My.Computer.FileSystem.CreateDirectory(new_flightnum_directory)
'Now create new subDirectories
My.Computer.FileSystem.CreateDirectory(new_video_directory)
MessageBox.Show("The new flight directory & video CAM subdirectories have been created! The videos will be moved and files converted now which will take some time.")
Catch ex As Exception
MessageBox.Show("Doh! The flight num or CAM directory could not be created! Error: " & ex.Message, "Error creating directory.", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
'***END CREATE STORAGE DIRECTORY STRUCTURE ***
MessageBox.Show("new merged video file has been created in " & dir & Me.BUILD.Text & "\" & Me.CAM.Text)
End Sub
End Class
The problem is that the & operator in VB is used only to concatenate System.String objects. It's stricter than using + to concatenate. You can't use it to concatenate a String and a System.IO.FileInfo object together. What you want is to get the file name from the FileInfo object. It has an attribute, FileInfo.FullName which will return the full path of the file as a String - from the documentation.
Try instead:
For Each foundFile As String In My.Computer.FileSystem.GetFiles(video_card_dir, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.MTS")
Dim movedFileInfo As New System.IO.FileInfo(foundFile)
psi.Arguments = "ffmpeg -i " & movedFileInfo.FullName & " -vcodec -c libx264 " & movedFileInfo.FullName & ".mp4"
psi.ToString()
proc = Process.Start(psi)
Next
If you want to replace the .mts extension with .mp4, instead of simply appending .mp4 as this code does, please see this question.

Displaying the output of Process.Start

I have a Process.Start command that I would like to see the output of, but the new window is opening and closing too quickly for me to see anything. Here is the code I have so far that I'm working with:
System.Diagnostics.Process.Start(Environment.GetEnvironmentVariable("VS110COMNTOOLS") & "..\Ide\MSTEST.EXE", "/Testsettings: """ & rwSettings & "" & " /Testcontainer: """ & rwContainer & "" & " /Resultsfile: """ & rwResults & "")
Unfortunately as I try to debug this if I allow this to run it flashes up the window but doesn't let me see what the error is, or if it's running successfully at all. I'm using VS2012 so I might just not be looking at the right view when I'm debugging.
Here is some code taen out of the middle of some logic, so it is not standalone. You can use ProcessStartInfo() and Process() to have more control:
Dim start_info As New ProcessStartInfo("sqlcmd", cmd)
start_info.UseShellExecute = False
start_info.CreateNoWindow = True
start_info.RedirectStandardOutput = True
start_info.RedirectStandardError = True
' Make the process and set its start information.
Dim proc As New Process()
proc.StartInfo = start_info
Dim dt As Date = Now()
' Start the process.
proc.Start()
' Attach to stdout and stderr.
Dim std_out As StreamReader = proc.StandardOutput() ' will not continue until process stops
Dim std_err As StreamReader = proc.StandardError()
' Retrive the results.
Dim sOut As String = std_out.ReadToEnd()
Dim sErr As String = std_err.ReadToEnd()

VB.Net process exits as soon as I attempt to read standard output or error

Initial Problem
I apologize if this issue has been raised and addressed elsewhere; I searched this site, and Google at large without any luck.
I'm trying to write a simple VB.Net Windows Forms Application to allow a user to run the Windows File Compare program (fc.exe) with a very simple GUI ("browse" buttons to select files, checkboxes to select modifiers, and a textbox for the output).
The problem is that whenever I try to read the standard output or error from the process, it immediately stops, and nothing is output. I've verified that the process arguments are correct by setting "createnowindow" to False and not redirecting Output or Errors.
To see if the process is actually running or not, I put a "while" loop after proc.start:
Do While proc.HasExited = False
textbox.AppendText(i & vbNewLine)
i += 1
Loop
If the process runs normally, I get a count up to about 80 or 90. If I do anything at all with the standardoutput or standarderror, the textbox only shows the initial value of "0". By "anything at all", I mean assigning the proc.StandardOutput.ReadToEnd to a variable. If I use proc.StandardOutput.Peek, it returns a -1 and the loop remains at 0.
I've noticed that if I only redirect either Output or Error (but not both), and I enable the process to open a new window, the new window is empty and immediately exits (even if I'm not attempting to read the redirected stream in my code), whereas if neither is redirected, it displays a few pages of results, then exits. I don't know if this is normal, or if the File Compare executable is somehow mixing the Output and Error streams to generate its output, or if something like that is even possible.
I'm extremely new to coding in general (I've been working with VB.net for about a month, and that's the extent of my programming experience), so my I'm aware that my troubleshooting and assumptions may be completely off base, and I appreciate any assistance anyone can provide. As it is, I'm completely floundering, and my inexperience is making it difficult to look for alternatives (for instance, I can't figure out how to correctly handle asynchronous output). For reference, here's my embarrassingly clunky code as it currently stands:
Dim cmdinput As String = """" & file1path & """" & " " & """" & file2path & """"
Dim cmdmods As String = " "
Dim i As Integer = 0
Dim proc As New Process
proc.StartInfo.CreateNoWindow = True
proc.StartInfo.UseShellExecute = False
proc.StartInfo.FileName = "C:\Windows\System32\fc.exe"
proc.StartInfo.Arguments = cmdinput & cmdmods
proc.StartInfo.RedirectStandardOutput = True
proc.StartInfo.RedirectStandardError = True
proc.Start()
proc.StandardOutput.ReadToEnd()
Do While proc.HasExited = False
scanbox.AppendText(i & vbNewLine)
i += 1
Loop
Possible Solution
After Hans Passant pointed out that I should be seeing errors, if nothing else, I messed around with my code and was able to get a result, though a less than optimal one. Instead of running FC.exe directly, I ran CMD.exe. I had tried this before with no luck, but that's because CMD.exe doesn't accept "fc " as process.startinfo.arguments.
I passed the "fc " to cmd.exe with proc.standardinput.writeline(). At this point I was able to read CMD.exe's redirected output. I still have no idea why I can't directly read FC.exe, but this is a pretty good band-aid in the meantime. On the off chance that anyone else feels the need to add a GUI to a perfectly good command-line executable and runs into problems, here's my code:
Public Sub compare()
Dim cmdinput As String = "fc " & """" & file1path & """" & " " & """" & file2path & """"
Dim cmdmods As String = " "
Dim proc As New Process
proc.StartInfo.CreateNoWindow = True
proc.StartInfo.UseShellExecute = False
proc.StartInfo.FileName = "C:\Windows\System32\cmd.exe"
proc.StartInfo.Arguments = cmdinput & cmdmods
proc.StartInfo.RedirectStandardOutput = True
proc.StartInfo.RedirectStandardError = True
proc.StartInfo.RedirectStandardInput = True
proc.Start()
proc.StandardInput.WriteLine(cmdinput)
proc.StandardInput.Close()
scanbox.AppendText(proc.StandardOutput.ReadToEnd)
proc.WaitForExit()
proc.Close()
proc.Dispose()
End Sub
I Greatly appreciate the patience from Hans Passant and Dan Verdolino in offering suggestions to my rambling question. I've been hammering my head against a wall for a week trying to kludge together some way of doing this.
Solution
Instead of running FC.exe directly, I ran CMD.exe. I had tried this before with no luck, but that's because CMD.exe doesn't accept "fc (args)" as process.startinfo.arguments.
I passed the "fc (args)" to cmd.exe with proc.standardinput.writeline(). At this point I was able to read CMD.exe's redirected output. I still have no idea why I can't directly read FC.exe's output or errors, but this is a pretty good band-aid in the meantime. On the off chance that anyone else feels the need to add a GUI to a perfectly good command-line executable and runs into problems, here's my code:
Public Sub compare()
Dim cmdinput As String = "fc " & """" & file1path & """" & " " & """" & file2path & """"
Dim cmdmods As String = " "
Dim proc As New Process
proc.StartInfo.CreateNoWindow = True
proc.StartInfo.UseShellExecute = False
proc.StartInfo.FileName = "C:\Windows\System32\cmd.exe"
proc.StartInfo.Arguments = cmdinput & cmdmods
proc.StartInfo.RedirectStandardOutput = True
proc.StartInfo.RedirectStandardError = True
proc.StartInfo.RedirectStandardInput = True
proc.Start()
proc.StandardInput.WriteLine(cmdinput)
proc.StandardInput.Close()
scanbox.AppendText(proc.StandardOutput.ReadToEnd)
proc.WaitForExit()
proc.Close()
proc.Dispose()
End Sub
Private Delegate Sub InvokeWithString(ByVal text As String)
Public Sub StartFC()
Private psi As ProcessStartInfo
Private cmd As Process
Dim CMDINPUT As String = "fc " & """" & file1path & """" & " " & """" & file2path & """"
Dim FileToHit As String = "c:\windows\system32\fc.exe "
psi = New ProcessStartInfo(FileToHit)
Dim systemencoding As System.Text.Encoding = _
System.Text.Encoding.GetEncoding(Globalization.CultureInfo.CurrentUICulture.TextInfo.OEMCodePage)
With psi
.Arguments = CMDINPUT
.UseShellExecute = False ' Required for redirection
.RedirectStandardError = True
.RedirectStandardOutput = True
.RedirectStandardInput = True
.CreateNoWindow = True
.StandardOutputEncoding = systemencoding
.StandardErrorEncoding = systemencoding
End With
' EnableraisingEvents is required for Exited event
cmd = New Process With {.StartInfo = psi, .EnableRaisingEvents = True}
AddHandler cmd.ErrorDataReceived, AddressOf Async_Data_Received
AddHandler cmd.OutputDataReceived, AddressOf Async_Data_Received
AddHandler cmd.Exited, AddressOf CMD_Exited
cmd.Start()
pID1 = cmd.Id
cmd.BeginOutputReadLine()
cmd.BeginErrorReadLine()
Me.txtInputStringIn.Select() ' textbox where you can send more commands.
End Sub
'This event fires when process exited
Private Sub CMD_Exited(ByVal sender As Object, ByVal e As EventArgs)
'Me.Close()
MessageBox.Show("Process is exited.")
End Sub
'This part calls when Output received
Private Sub Async_Data_Received(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
Me.Invoke(New InvokeWithString(AddressOf Sync_Output), e.Data)
End Sub
Private Sub Sync_Output(ByVal text As String)
'an output textbox will show the output of the command prompt.
txtOutPut.AppendText(text & Environment.NewLine)
txtOutPut.ScrollToCaret()
End Sub