Need to open file through VB.net on another directory - vb.net

Through my form, I open a .exe which is located in a folder inside debug so:
\bin\Debug\folder\ .exe
The .exe opens and creates 3 different files then closes. It is meant to create them in the same folder as the .exe but instead creates it in the Debug folder when opened through VB.net using Process.Start().
Would anyone have a possible fix for this so I don't have to move the files?
EDIT
(the .exe itself creates the files, some things may be declared outside of this sub)
Private Sub btnRunExe_Click(sender As Object, e As EventArgs) Handles btnRunExe.Click
If AcptEULA.Checked = True Then
Localpath = Application.StartupPath() + "\MCserver" + "\minecraft_server." + txtVersion.Text + ".exe"
Downloadpath = "https://s3.amazonaws.com/Minecraft.Download/versions/" + txtVersion.Text + "/minecraft_server." + txtVersion.Text + ".exe"
LocalpathParent = Application.StartupPath() + "\MCserver"
Try
Dim dirs As String() = Directory.GetFiles(LocalpathParent, "minecraft_server*.exe")
Dim dir As String
For Each dir In dirs
Process.Start(dir)
Next
Catch
'Console.WriteLine("The process failed: {0}", e.ToString())
End Try
ElseIf AcptEULA.Checked = False Then
MsgBox("You must accept the Minecraft EULA before continuing")
End If
End Sub

Process.Start could be used with a ProcessStartInfo instance in which you could set the WorkingDirectory property.
Dim psi As ProcessStartInfo = New ProcessStartInfo()
psi.WorkingDirectory = LocalpathParent
For Each fileName In Directory.EnumerateFiles(LocalpathParent, "minecraft_server*.exe")
psi.FileName = fileName
Process.Start(psi)
Next
Notice that I have changed the Directory.GetFiles with Directory.EnumerateFiles that allows you to process a file while you loop over the folder files without loading all the filenames in memory inside an array. If you still want to use GetFiles then it is
Dim psi As ProcessStartInfo = New ProcessStartInfo()
psi.WorkingDirectory = LocalpathParent
Dim files as String() = Directory.GetFiles(LocalpathParent, "minecraft_server*.exe")
For Each fileName In files
psi.FileName = fileName
Process.Start(psi)
Next
If you look at the ProcessStartInfo documentation on MSDN you could find a lot of other useful properties to fine tune how your program executes.

Related

What is the proper way to save an existing file to a user's computer using a SaveFileDialog?

I have a vb.net windows app that creates a PDF. After creation, I want to prompt the user where they want to save the file. The default save folder is different than the folder of the created PDF. I get the SaveDialog box to come up with the default folder and file name that I want. If I choose "Save", I get a message saying that the file does not exist and none of the code below the ShowDialog is executed (I'm sure that I'm doing that part wrong as well).
Dim saveFileDialog1 As New SaveFileDialog
saveFileDialog1.InitialDirectory = MyDocsFolder
saveFileDialog1.FileName = "Report.pdf"
saveFileDialog1.Title = "Save Report"
saveFileDialog1.CheckFileExists = True
saveFileDialog1.CheckPathExists = True
saveFileDialog1.DefaultExt = "pdf"
saveFileDialog1.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
saveFileDialog1.ShowDialog()
If saveFileDialog1.ShowDialog = DialogResult.OK Then
If saveFileDialog1.FileName() <> "" Then
Dim newStream As FileStream = File.Open(newFile, FileMode.Open)
Dim pdfStream As New FileStream(saveFileDialog1.FileName, FileMode.Create)
newStream.CopyTo(fs, FileMode.Append)
newStream.Close()
fs.Close()
End If
End If
you can do it like this:
Imports Microsoft.WindowsAPICodePack.Dialogs
Public NotInheritable Class Form1
Private Sub ButtonSave_Click(sender As Object, e As EventArgs) Handles ButtonSave.Click
Dim Path As String
Using SFD1 As New CommonSaveFileDialog
SFD1.Title = "Where should the file be saved?"
SFD1.Filters.Add(New CommonFileDialogFilter("PDF", ".pdf"))
SFD1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
If SFD1.ShowDialog() = CommonFileDialogResult.Ok Then
Path = SFD1.FileName
Else
Return
End If
End Using
Dim dest As IO.FileInfo
Using fs As IO.FileStream = IO.File.Create(Path & ".pdf")
dest = My.Computer.FileSystem.GetFileInfo(fs.Name)
End Using
End Sub
End Class
Please note that I am using a FileDialog that I downloaded from Visual Studios' own Nuget Package Manager. See image. You don't have to do that, but I prefer this FileDialog because it offers more options than the one that is already included.
So the user enters the file name; thus the path results. In my code example, this creates a blank PDF. It cannot be opened like this yet.
So that something is written in the PDF, you can download itext7 (also via NuGet).
Then, you write Imports iText.Kernel.Pdf,
Imports iText.Kernel.Utils and in your sub Dim pdfwriter As New PdfWriter(dest) with ‘dest’ from above.
I am so blind and stupid...
saveFileDialog1.CheckFileExists = True
Sorry for wasting anyone's time.

Create and write to file > start application > delete file in VB.NET

I'm trying to create a VB.NET application which writes multiple lines of text into a text file, then starts an application and after the application started, deletes the text file.
How exactly can I realize that?
--
Edit:
I now got this code:
Dim iniFile As String = Application.StartupPath + "\settings.ini"
If System.IO.File.Exists(iniFile) = True Then
File.Delete(iniFile)
End If
If System.IO.File.Exists(iniFile) = False Then
File.Create(iniFile)
End If
Dim fileStr As String() = {"line1", "line2", "line3"}
File.WriteAllLines(iniFile, fileStr)
Dim p As Process = Process.Start(Application.StartupPath + "\app.exe")
p.WaitForInputIdle()
If System.IO.File.Exists(iniFile) = True Then
File.Delete(iniFile)
End If
The only problem I got, is that VS is telling me, the file is in use. Between creating and editing the file. Any ideas for that?
Your code is starting the app and then moving straight on to delete the ini file.
You need to wait for the process to exit first before you continue with deleting the ini file
E.g
{code to create ini file}
'Start the process.
Dim p As Process = Process.Start(Application.StartupPath + "\app.exe")
'Wait for the process window to complete loading.
p.WaitForInputIdle()
'Wait for the process to exit.
p.WaitForExit()
{code to delete ini file}
Full example here: https://support.microsoft.com/en-us/kb/305368
Just use File.WriteAllText
Note: As others already mentioned, you should check against True in your last If
If System.IO.File.Exists(Application.StartupPath + "\settings.ini") = False Then
File.Create(Application.StartupPath + "\settings.ini")
End If
Dim fileStr As String() = {"line1", "line2", "line3"}
System.IO.File.WriteAllText(Application.StartupPath + "\settings.ini", [String].Join(Environment.NewLine, fileStr))
Process.Start(Application.StartupPath + "\app.exe")
If System.IO.File.Exists(Application.StartupPath + "\settings.ini") = True Then
File.Delete(Application.StartupPath + "\settings.ini")
End If
Use File.WriteAllLines since it
Creates a new file, write the specified string array to the file, and then closes the file. [...] If the target file already exists, it is overwritten.
msdn
Also you should use Path.Combine to setup your path
Dim path as String = Path.Combine(Application.StartupPath, "settings.ini")
Dim fileStr As String() = {"line1", "line2", "line3"}
File.WriteAllLines(path, fileStr)
Use the Path.Combine for the Process.Start and File.Delete too.

VB.NET Communicating with console app and sending parameters

I'm creating myself a GUI for a program that can be used in CMD, a CLI.
The program has the following input:
Ex: extractor.exe filename.rar newfilename.zip -c <password for achive>
filename.rar = the original file
newfilename.zip = the file to be created with new format
-c a command meaning key
<password...> - here comes the archive password.
It's great on CMD, but I would like to make a GUI.
I do it in VB and so:
For filename.rar I have one textbox that goes filled with a path specified by user using OpenFileDialog1.
For newfilename.zip I use a savefiledialog and a textbox: The textbox gets the path specified by user
Another textbox3 for the password and a button to call extractor.exe:
How can I pass these arguments to extractor?
I have tried with
argument = textbox1.text + textbox2.text + "-c" + textbox3.text
The program starts but simply closes as it simply doesn't get the parameters.
I have also tried this:
Dim psi As ProcessStartInfo
Dim procname = "extractor.exe"
Dim filename = TextBox1.Text
Dim newfile = TextBox3.Text
Dim key = TextBox2.Text
Dim args = ("extract" + filename + newfile + "-k" + key)
psi = New ProcessStartInfo(procname, args)
Dim proc As New Process()
proc.StartInfo = psi
proc.Start()
No luck. I'm able to send 1 parameter if I do like
argument = "extract" but i have multiple arguments that needs to be fetched from textboxes....is there a way?
Thanks!

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.

How to Pick a File when I have only part of the name?

I am building an application that opens all kinds of files from different folders. I need to open the application by subsequently opening a Powerpoint presentation which has "1" at the beginning of its name. How should I do this?
I wrote the following code but it works only if I put in the exact name:
If (System.IO.File.Exists("FilePath\1*")) Then
'Lists File Names from folder & when selected, opens selected file in default program
Dim file3dopen As New ProcessStartInfo()
With file3dopen
.FileName = "TheFilepath\1*"
.UseShellExecute = True
End With
Process.Start(file3dopen)
Else
MsgBox("No Such File Exists")
End If
You need to look for all the files in that directory using Directory.GetFiles(string path, string pattern).
Dim files As String() = Directory.GetFiles("\FilePath", "1*")
If files.Length > 0 Then ' file found
Dim file3dopen As New ProcessStartInfo()
With file3dopen
.FileName = files(0)
.UseShellExecute = True
End With
Process.Start(file3dopen)
Else
'file not found
MsgBox("No Such File Exists")
End If