Process.Start not passing along Arguments - vb.net

I have a bat file that runs the following perfectly fine:
Bec.exe --f=Config.cfg
Now in vb.net I have a button that starts the same exe with the same arguments, and outputs to a rtb. However it does not pass along the arguments for some reason, I don't know why. Can anyone help?
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim cmdProcess As Process
cmdProcess = New Process()
cmdProcess.StartInfo.FileName = """" & TextBox2.Text & """" 'normally this is C:\ServerTools\Bec.exe
cmdProcess.StartInfo.Arguments = """" & TextBox1.Text & """" 'normally is --f=Config.cfg
cmdProcess.StartInfo.RedirectStandardOutput = True
cmdProcess.StartInfo.UseShellExecute = False
If cmdProcess.Start() Then
RichTextBox2.Text = cmdProcess.StandardOutput.ReadToEnd
Else
' Failed to execute
End If
End Sub
Also I'll provide a reference of the accepted options to the .exe I'm starting
Options:
-h, --help show this help message and exit
-f FILENAME, --file=FILENAME

Try to use the ProcessStartInfo.WorkingDirectory property.

I've always done this by creating a separate ProcessStartInfo object and passing that into the Process.Start() method.
ProcessStartInfo psi = new ProcessStartInfo("filename.txt", "-arg1 -arg2");
Process.Start(psi);

You should not quote the arguments, nor the exe path
cmdProcess.StartInfo.FileName = TextBox2.Text
cmdProcess.StartInfo.Arguments = TextBox1.Text

I've come across a solution, apparently I had to be running my program in the same directory as the exe I was executing. the -f Config.cfg argument is normally based off the location of where Bec.exe is, well when I was calling it through my program it was basing it off of my programs location, so now that I have my program in the same directory it's working now.

Related

Do...Loop starts too quickly, how to brake it?

With my program, user have to download and save csv files to two different specific directories. Unfortunately automatic downloading not possible. To download file I use command WebBrowser1.Navigate(url), which run php script on the target web page and after one second webBrowser ask path where I or user want to download file. After that again button click and .Navigate to download second one.
But I have to be sure, that user had download file exactly to the specific directory and first, I want to check if file exists there. And here problems are starts. Because of small delay before "Save" possibility, program run immediately Do...Loop process and "Save" window doesn't even come. Also I tried to use thread.sleep, but it doesn't help. Because it immediately go to sleep and "save" window have not time to present. After sleep it immediately starts Do...Loop process.
Is here some other instruments to say to my program, that it wait a little and continue to run code after user "Save" file?
Here is My code:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim kraporttila As String
Dim dt1 As Date = DateTimePicker1.Value
Dim dt2 As Date = DateTimePicker2.Value
Dim faa As String = dt1.ToString("yyyy-MM-dd")
Dim fla As String = dt2.ToString("yyyy-MM-dd")
Dim ddla As String = dt2.ToString("MM.yy")
Dim kuitti As Uri = New Uri("https:url/kuitti.php?faa=" & faa & "&fla=" & fla & "&fk_e=&fa_e=&fm=&ftil=&kuittiexportcsv=Lataa%CSV")
WebBrowser1.Navigate(kuitti)
Button2.Visible = False
Do While
If System.IO.File.Exists(kraporttila) = True Then
Button3.Text = "Lataa maksuvirheet"
Button3.Visible = True
Label3.Text = "Nyt lataa maksuviheet ja tellenna kansioon ""C:\Users\Ivan\" & ddla & "\Laskutukset ja Maksuvirheet\Maksuvirheet"""
Exit Do
Else
Continue Do
End If
Loop
End Sub

Process.Start arguments not working

I am trying to start a process with two parameters that will run from a cmd prompt window just fine. The problem comes when I try to launch it via process.start.
In the cmd window, it looks like this.
D:\Projects\MyProg.exe "D:\Projects\MyScript.txt" "D:\Projects\MyInputData.txt"
When I try to build the arguments in .NET it puts double quotes around the entire string and it looks like this. The program doesn't interpret it as two parameters and just stops. If I add double quotes around each argument it still misinterprets it.
I know it is the MyProg.exe issue (vendor program that I can't change) but is there a way to send this command so it will work?
myProcess.StartInfo.Arguments = "D:\Projects\MyScript.txt D:\Projects\MyInputData.txt"
When I add double quotes it sort of works, the program starts but then has a problem and just stops.
myProcess.StartInfo.Arguments = """D:\Projects\MyScript.txt"" ""D:\Projects\MyInputData.txt"""
I'm not quite sure what D:\Projects\MyProg.exe is doing but following sample is working for. Two variable strings are declared. The two strings indicate two argument parameters I want to use with the executable.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'// Set first file parameter to the executable
Dim sourceFileName As String = "source.txt"
'// Set second file parameter to the executable
Dim targetFileName As String = "target.txt"
'// Create a new ProcessStartInfo
Dim p As New ProcessStartInfo
'// Specify the location of the binary
p.FileName = "D:\_working\ConsoleApplication3.exe"
'// Use these arguments for the process
p.Arguments = " """ & sourceFileName & """ """ & targetFileName & """ -optionalPara"
' Use a hidden window
'p.WindowStyle = ProcessWindowStyle.Hidden
' Start the process
Process.Start(p)
End Sub
End Class
See resulting screenshot:

VB.NET 2010 - Process.Start("filePath\Test.bat") not opening test.bat?

I have been working on some vb.net 2010 coding and I am stuck on a piece of code that I dont know how to fix it, so thats why I ask you to maybe help me with this code.
Code:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim url As New System.Uri("http://example/one/")
Dim req As System.Net.WebRequest
req = System.Net.WebRequest.Create(url)
Dim resp As System.Net.WebResponse
Dim filePath As String
filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\examplepath"
Try
resp = req.GetResponse()
resp.Close()
req = Nothing
Process.Start("filePath\Test.exe")
Catch ex As Exception
req = Nothing
Me.Close()
End Try
End Sub
Problem:
The file in %APPDATA%\ExamplePath\Test.bat doesn't open.
I hope you can help me :)
This line seems the problem:
Process.Start("filePath\Test.exe")
Here you're putting a variable as a string, which of course won't work. Instead, concatenate it with the file name:
Process.Start(filePath & "\Test.exe")
That will work, but a better way to handle the file system is to use the Path class and the Combine method to handle a path that has multiple parts:
Process.Start(Path.Combine(filePath, "Test.exe"))
This deals with putting the correct separator and the fact that it may or may not have a trailing backslash.
You need to use cmd for opening batfiles:
Process.Start("cmd", "/c foobar/test.bat")
be carefull, if the filepath contains spaces you have to add extra "" to make it work:)
your problem was, that a .bat file is not a process to start, only a file
Try declaring a new process and specify the WorkingDirectory property.
Use the following code to achieve this
Dim myProcess As New Process
myProcess.StartInfo.WorkingDirectory = Environment.GetFolderPath(SpecialFolder.ApplicationData)
myProcess.StartInfo.FileName = "Test.bat"
myProcess.Start()

How to check when a powershell script is done running with Visual Studio

I am running a powershell script from within my app. I can start it and it completes without problem, but how do I check when its done? I need to do other actions, Only once its complete. Here is what I have, for a bit of reference:
Public Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If requiredEnd = True And requiredPass = True And requiredPath = True And requiredSheet = True And requiredStart = True And requiredUser = True Then
For I = 0 To 7
objWriter.WriteLine(aryText(I))
Next
objWriter.Close()
Dim p As Process
p.Start("powershell", "-ExecutionPolicy ByPass -windowstyle hidden -file .\\Excel.ps1")
p.WaitForExit()
If p.HasExited = True Then
MsgBox("The Process Has Been Completed!")
Application.Exit()
End If
Else
If requiredEnd = False Or requiredPass = False Or requiredSheet = False Or requiredStart = False Or requiredUser = False Then
MessageBox.Show("You Have Missing Required Fields!")
Else
MessageBox.Show("That Is Not A Valid File!")
End If
End If
End Sub
Thanks for the help! Also, I am a beginner at this, so could you do a bit of an explanation on how it works if it isn't super straight forward? Thanks again.
Edit: I realize I forgot the key point: I can close the script, but I need to know if it exited successfully. So a way to check errors, basically.
Why not use a runspace to execute your powershell code in-process, instead of shelling out to an external application? Most of the code you see for this is in C# but you can of course do it in VB.net as well:
' create Powershell runspace
Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
' open it
MyRunSpace.Open()
' create a pipeline and feed it the script text
Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline()
MyPipeline.Commands.AddScript(scriptText)
' add an extra command to transform the script output objects into nicely formatted strings
' remove this line to get the actual objects that the script returns. For example, the script
' "Get-Process" returns a collection of System.Diagnostics.Process instances.
MyPipeline.Commands.Add("Out-String")
' execute the script
Dim results As Collection(Of PSObject) = MyPipeline.Invoke()
' close the runspace
MyRunSpace.Close()
This code is taken from this MSDN blog which has a much more thorough and complete example application, but the basic idea here is to run the code natively in your application and then you can get the output any way you like to test for errors.

Open, Launch or Show a file for the user to read or write in vb.net

It sounds very simple but I have searched and cannot seem to find a way to open a log file which the user just created from my windows form app. The file exits I just want to open it after it is created.
I have a Dim path As String = TextBox1.Text and once the user names and clicks ok on the savefiledialog I have a msgbox that says "Done" and when you hit OK I have tried this
FileOpen(FreeFile, path, OpenMode.Input) but nothing happens. I just want it to open the log and show it to the user so they can edit or save it again or anything.
This is where I got the above code.
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.filesystem.fileopen.aspx
Searching is difficult because everyone is trying to "Open" a file and process it during runtime. I am just trying to Show a file by Launching it like someone just double clicked it.
Here is the entire Export Button click Sub. It basically writes listbox items to file.
Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
Dim sfd As New SaveFileDialog
Dim path As String = TextBox1.Text
Dim arypath() As String = Split(TextBox1.Text, "\")
Dim pathDate As String
Dim foldername As String
foldername = arypath(arypath.Length - 1)
pathDate = Now.ToString("yyyy-MM-dd") & "_" & Now.ToString("hh;mm")
sfd.FileName = "FileScannerResults " & Chr(39) & foldername & Chr(39) & " " & pathDate
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
sfd.Filter = "Text files (*.txt)|*.txt|CSV Files (*.csv)|*.csv"
sfd.ShowDialog()
path = sfd.FileName
Using SW As New IO.StreamWriter(path)
If CkbxFolder.Checked = True Then
SW.WriteLine("Folders")
For Each itm As String In ListBox1.Items
SW.WriteLine(itm)
Next
End If
If CkbxFiles.Checked = True Then
SW.WriteLine("Files")
For Each itm As String In ListBox2.Items
SW.WriteLine(itm)
Next
End If
End Using
MsgBox("Done...")
FileOpen(FreeFile, path, OpenMode.Input) 'Why can't I open a file for you...
End Sub
Do not use the old VB6 methods. They are still here for compatibility reason, the new code should use the more powerful methods in the System.IO namespace.
However, as said in comments, FileOpen don't show anything for you, just opens the file
You coud write
Using sr = new StreamReader(path)
Dim line = sr.ReadLine()
if !string.IsNullOrEmpty(line) Then
textBoxForLog.AppendText(line)
End If
End Using
or simply (if the file is not too big)
Dim myLogText = File.ReadAllText(path)
textBoxForLog.Text = myLogText
As alternative, you could ask the operating system to run the program associated with the file extension and show the file for you
Process.Start(path)
To get the same behavior as if the user double-clicked it, just use System.Diagnostics.Process, and pass the filename to it's Start method:
Process.Start(path)
This will open the file using whatever the default application is for that filename based on its extension, just like Explorer does when you double-click it.