Process.Start arguments not working - vb.net

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:

Related

Add a path to a code VB.net / visual basic

how do I add a path to a code where "HERE_HAS_TO_BE_A_PATH" is. When I do, Im getting an error message. The goal is to be able to specific the path where is the final text file saved.
Thanks!
Here is a code:
Dim newFile As IO.StreamWriter = IO.File.CreateText("HERE_HAS_TO_BE_A_PATH")
Dim fix As String
fix = My.Computer.FileSystem.ReadAllText("C:\test.txt")
fix = Replace(fix, ",", ".")
My.Computer.FileSystem.WriteAllText("C:\test.txt", fix, False)
Dim query = From data In IO.File.ReadAllLines("C:\test.txt")
Let name As String = data.Split(" ")(0)
Let x As Decimal = data.Split(" ")(1)
Let y As Decimal = data.Split(" ")(2)
Let z As Decimal = data.Split(" ")(3)
Select name & " " & x & "," & y & "," & z
For i As Integer = 0 To query.Count - 1
newFile.WriteLine(query(i))
Next
newFile.Close()
1) Use a literal string:
The easiest way is replacing "HERE_HAS_TO_BE_A_PATH" with the literal path to desired output target, so overwriting it with "C:\output.txt":
Dim newFile As IO.StreamWriter = IO.File.CreateText("C:\output.txt")
2) Check permissions and read/write file references are correct:
There's a few reasons why you might be having difficulties, if you're trying to read and write into the root C:\ directory you might be having permissions issues.
Also, go line by line to make sure that the input and output files are correct every time you are using one or the other.
3) Make sure the implicit path is correct for non-fully qualified paths:
Next, when you test run the program, it's not actually in the same folder as the project folder, in case you're using a relative path, it's in a subfolder "\bin\debug", so for a project named [ProjectName], it compiles into this folder by default:
C:\path\to\[ProjectName]\bin\Debug\Program.exe
In other words, if you are trying to type in a path name as a string to save the file to and you don't specify the full path name starting from the C:\ drive, like "output.txt" instead of "C:\output.txt", it's saving it here:
C:\path\to\[ProjectName]\bin\Debug\output.txt
To find out exactly what paths it's defaulting to, in .Net Framework you can check against these:
Application.ExecutablePath
Application.StartupPath
4) Get user input via SaveFileDialogue
In addition to a literal string ("C:\output.txt") if you want the user to provide input, since it looks like you're using .Net Framework (as opposed to .Net Core, etc.), the easiest way to set a file name to use in your program is using the built-in SaveFileDialogue object in System.Windows.Forms (like you see whenever you try to save a file with most programs), you can do so really quickly like so:
Dim SFD As New SaveFileDialog
SFD.Filter = "Text Files|*.txt"
SFD.ShowDialog()
' For reuse, storing file path to string
Dim myFilePath As String = SFD.FileName
Dim newFile As IO.StreamWriter = IO.File.CreateText(myFilePath) ' path var
' Do the rest of your code here
newFile.Close()
5) Get user input via console
In case you ever want to get a path in .Net Core, i.e. with a console, the Main process by default accepts a String array called args(), here's a different version that lets the user add a path as the first parameter when running the program, or if one is not provided it asks the user for input:
Console.WriteLine("Hello World!")
Dim myFilePath = ""
If args.Length > 0 Then
myFilePath = args(0)
End If
If myFilePath = "" Then
Console.WriteLine("No file name provided, please input file name:")
While (myFilePath = "")
Console.Write("File and Path: ")
myFilePath = Console.ReadLine()
End While
End If
Dim newFile As IO.StreamWriter = IO.File.CreateText(myFilePath) ' path var
' Do the rest of your code here
newFile.Close()
6) Best practices: Close & Dispose vs. Using Blocks
In order to keep the code as similar to yours as possible, I tried to change only the pieces that needed changing. Vikyath Rao and Mary respectively pointed out a simplified way to declare it as well as a common best practice.
For more information, check out these helpful explanations:
Can any one explain why StreamWriter is an Unmanaged Resource. and
Should I call Close() or Dispose() for stream objects?
In summary, although streams are managed and should garbage collect automatically, due to working with the file system unmanaged resources get involved, which is the primary reason why it's a good idea to manually dispose of the object. Your ".close()" does this. Overrides for both the StreamReader and StreamWriter classes call the ".dispose()" method, however it is still common practice to use a Using .. End Using block to avoid "running with scissors" as Enigmativity puts it in his post, in other words it makes sure that you don't go off somewhere else in the program and forget to dispose of the open filestream.
Within your program, you could simply replace the "Dim newFile As IO.StreamWriter = IO.File.CreateText("C:\output.txt")" and "newFile.close()" lines with the opening and closing statements for the Using block while using the simplified syntax, like so:
'Dim newFile As IO.StreamWriter = IO.File.CreateText(myFilePath) ' old
Using newFile As New IO.StreamWriter(myFilePath) ' new
Dim fix As String = "Text from somewhere!"
newFile.WriteLine(fix)
' other similar operations here
End Using ' new -- ensures disposal
'newFile.Close() ' old
You can write that in this way. The stream writer automatically creates the file.
Dim newFile As New StreamWriter(HERE_HAS_TO_BE_A_PATH)
PS: I cannot mention all these in the comment section as I have reputations less than 50, so I wrote my answer. Please feel free to tell me if its wrong
regards,
vikyath

Moving Files From One Folder To Another VB.Net

I am trying to figure out how to move 5 files
settings.txt
settings2.txt
settings3.txt
settings4.txt
settings5.txt
from one folder to another.
Although I know what the file names will be and what folder Name they will be in, I don't know where that folder will be on the Users computer.
My thought process is to use a FolderBrowseDialog which the user can browse to where the Folder is, and then when OK is pressed, it will perform the File copy to the destination folder, overwriting what's there.
This is what I have so far.
Dim FolderPath As String
Dim result As Windows.Forms.DialogResult = FolderBrowserImport.ShowDialog()
If result = DialogResult.OK Then
FolderPath = FolderBrowserImport.SelectedPath & "\"
My.Computer.FileSystem.CopyFile(
FolderPath & "settings.txt", "c:\test\settings.txt", overwrite:=True)
ElseIf result = DialogResult.Cancel Then
Exit Sub
End If
Rather than run this 5 times, is there a way where it can copy all 5 files at once
I know why IdleMind recommended the approach they did, but it would probably make for a bit more readable code to just list out the file names:
Imports System.IO
...
Dim result = FolderBrowserImport.ShowDialog()
If result <> DialogResult.OK Then Exit Sub
For Each s as String in {"settings.txt", "settings2.txt", "settings3.txt", "settings4.txt", "settings5.txt" }
File.Copy( _
Path.Combine(FolderBrowserImport.SelectedPath, s), _
Path.Combine("c:\test", s), _
True _
)
Next s
You can swap this fixed array out for a list that VB prepares for you:
For Each s as String in Directory.GetFiles(FolderBrowserImport.SelectedPath, "settings*.txt", SearchOption.TopDirectoryOnly)
File.Copy(s, Path.Combine("c:\test", Path.GetFilename(s)), True)
Next s
Tips:
It's usually cleaner to do a If bad Then Exit Sub than a If good Then (big load of indented code) End If - test all your known failure conditions at the start and exit the sub if anything fails, rather than arranging a huge amount of indented code
Use Path.Combine to combine path and filenames etc; it knows how to deal with stray \ characters
Use Imports to import namespaces rather than spelling everything out all the time (System.Windows.Forms.DialogResult - a winforms app will probably have all the necessaries imported already in the partial class so you can just say DialogResult. If you get a red wiggly line, point to the adjacent lightbulb and choose to import System.WIndows/Forms etc)
Once you have the selected folder, use a For loop to build up the names of the files you're looking for. Use System.IO.File.Exists() to see if they are there. Use System.IO.Path.Combine() to properly combine your folders with the filenames.
Here's a full example (without exception handling, which should be added):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FolderBrowserImport.ShowDialog() = DialogResult.OK Then
Dim FolderPath As String = FolderBrowserImport.SelectedPath
For i As Integer = 1 To 5
Dim FileName As String = "settings" & If(i = 1, "", i) & ".txt"
Dim FullPathFileName As String = System.IO.Path.Combine(FolderPath, FileName)
If System.IO.File.Exists(FullPathFileName) Then
Dim DestinationFullPathFileName = System.IO.Path.Combine("c:\test", FileName)
My.Computer.FileSystem.CopyFile(FullPathFileName, DestinationFullPathFileName, True)
Else
' possibly do something in here if the file does not exist?
MessageBox.Show("File not found: " & FullPathFileName)
End If
Next
End If
End Sub

Process.Start not passing along Arguments

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.

Running a advanced java call from VB.net

I need to run a small piece of Java code (Java is the only option in this case)
I have the jar file in the VB.net resources as JSSMCL(the extension is not required to run it, of this I am sure :P) I know I use Path.GetFullPath(My.Resources.ResourceManager.BaseName)
but no mater how I do it it fails, I have tried so many ways i have lost count!
this is the command that I need to run:
java -cp "JSSMCL.jar" net.minecraft.MinecraftLauncher username false
You can use System.Diagnostics.Process class and its method to start/run the external process.
Refer to the following code part to run the Command using Process
Sub Main()
' One file parameter to the executable
Dim sourceName As String = "ExampleText.txt"
' The second file parameter to the executable
Dim targetName As String = "Example.gz"
' New ProcessStartInfo created
Dim p As New ProcessStartInfo
' Specify the location of the binary
p.FileName = "C:\7za.exe"
' Use these arguments for the process
p.Arguments = "a -tgzip """ & targetName & """ """ & sourceName & """ -mx=9"
' Use a hidden window
p.WindowStyle = ProcessWindowStyle.Hidden
' Start the process
Process.Start(p)
End Sub
EDIT:
Use the Coding part like below, may be it works
-jar "compiler.jar" --js_output_file="myOutput.min.js" --js="input1.js" --js="input2.js"
Have a look at this link for your problem

Running script in selected path

I currently have this piece of code:
Sub Button1Click(sender As Object, e As EventArgs)
If dlgFolder.ShowDialog = Windows.Forms.DialogResult.OK Then
txtPath.Text = dlgFolder.SelectedPath
Try
Dim CopyFile As String = Path.Combine(Directory.GetCurrentDirectory, "pdftk.exe")
Dim CopyLocation As String = Path.Combine(dlgFolder.SelectedPath, "pdftk.exe")
Dim pyScript As String = Path.Combine(Directory.GetCurrentDirectory, "pdfmerge.py")
Dim pyLocation As String = Path.Combine(dlgFolder.SelectedPath, "pdfmerge.py")
System.IO.File.Copy(CopyFile, CopyLocation, True)
System.IO.File.Copy(pyScript, pyLocation, True)
Catch copyError As IOException
Console.WriteLine(copyError.Message)
End Try
End If
End Sub
This copies two files in the current working directory (which will be the default install folder) to the selected path from the Fodler Dialog Browser. This works correctly.
Now what I want to do is too run "pdfmerge.py" into the selected folder path. I tried the below code but the script is still running in the current working directory.
Sub BtnNowClick(sender As Object, e As EventArgs)
Dim myProcess As Process
Dim processFile As String = Path.Combine(dlgFolder.SelectedPath, "pdfmerge.py")
myProcess.Start(processFile, dlgFolder.SelectedPath)
End Sub
You can set the process's working directory.
Dim p As New ProcessStartInfo
p.FileName = Path.Combine(dlgFolder.SelectedPath, "pdfmerge.py")
p.WorkingDirectory = dlgFolder.SelectedPath
Process.Start(p)
One question: are you ensuring the dlgFolder.SelectedPath is correct? Without knowing the inner workings of your program, it appears possible to press BtnNow before Button1, meaning dlgFolder.SelectedPath won't have been set by the user.
Try using the overload of Process.Start() that takes 5 arguments.
Start ( _
fileName As String, _
arguments As String, _
userName As String, _
password As SecureString, _
domain As String _
)
You may be able to pass in null for userName and password, but if your directory is outside of the standard ones that you have permission for, you may need to put your username and password in. domain would be the working directory, I think.