Open a .exe that is in project folder - vb.net

The issue I am having is opening a program that's in my project folder after being published. here is my code:
Private Sub B_OpenCruc_Click(sender As Object, e As EventArgs) Handles B_OpenCruc.Click
System.Diagnostics.Process.Start("F:\Deploy\myprogram\Project\myprogram\myprogram\Crucible\Crucible.exe")
End Sub
now it works on my pc but not other pc's. I figured it's because its a full path. I also set properties to "content" and "copy always"
I tried using Dim Path As String = ("\My Project\Crucible\Crucible.exe") I would receive the following error
System.ComponentModel.Win32Exception: 'The system cannot find the file specified'
also this as well:
Severity Code Description Project File Line Suppression State
Warning Assembly 'Crucible\Crucible.exe' is incorrectly specified as a file. SCOfflineLoader
when I publish it.. the files are there but my program can't open it.
I can't seem to figure this out, is there a solution to this?
Basically the Goal I want to achieve is When I click a Button It will open a .exe
OR
When I click a button It will Open a .exe that the Target user already has (i.e notepad.exe)
Thanks.

You can use the Application.StartupPath property to get the directory where your application is running from.
Dim path As String = Path.Combine(Application.StartupPath, "Crucible.exe")
System.Diagnostics.Process.Start(path)

Related

Exe working only if started manually but I want it to start automatically

I have done a simple VB application with this code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim procName As String = Process.GetCurrentProcess().ProcessName
Dim processes As Process() = Process.GetProcessesByName(procName)
If processes.Length > 1 Then
Process.GetProcessesByName("keyinput")(0).Kill()
End If
End Sub
Public Sub type(ByVal int As Double, str As String)
For Each c As Char In str
SendKeys.Send(c)
System.Threading.Thread.Sleep(int * 1000)
Next
End Sub
Sub vai()
Dim line As String = ""
If File.Exists("trans.txt") Then
Using reader As New StreamReader("trans.txt")
Do While reader.Peek <> -1
line = reader.ReadLine()
type(0.155, line)
'SendKeys.Send(line)
SendKeys.Send("{ENTER}")
Loop
End Using
File.Delete("trans.txt")
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
vai()
End Sub
Basically the timer in it check if a file exists, read it and type the content simulating the keyboard.
I want this exe to start automatically when user login, it does it, apparently, I can see the form1 pop up but doesn't really works. Everyting is fine only if I run it manually by double-clicking the icon. Why and what can I do? Thanks
ps. i already tried to execute it with windows task manager, or putting a shortcut in the windows startup folder, or calling it from a cmd
EDIT:
when app starts automatically , process is running, but windows form is showing like this
Instead starting manually is showing like this:
I don't know this for a fact but I suspect that the issue is the fact that you are not specifying the location of the file. If you provide only the file name then it is assumed to be in the application's current directory. That current directory is often the folder that the EXE is in but it is not always and it can change. DO NOT rely on the current directory being any particular folder. ALWAYS specify the path of a file. If the file is in the program folder then specify that:
Dim filePath = Path.Combine(Application.StartupPath, "trans.txt")
If File.Exists(filePath) Then
Using reader As New StreamReader(filePath)
EDIT:
If you are running the application at startup by adding a shortcut to the user's Startup folder then, just like any other shortcut, you can set the working directory there. If you haven't set the then the current directory will not be the application folder and thus a file identified only by name will not be assumed to be in that folder.
If you are starting the app that way (which you should have told us in the question) then either set the working directory of the shortcut (which is years-old Windows functionality and nothing to do with VB.NET) or do as I already suggested and specify the full path when referring to the file in code. Better yet, do both. As I already said, DO NOT rely on the current directory being any particular folder, with this being a perfect example of why, but it still doesn't hurt to set the current directory anyway if you have the opportunity.
It was a Windows task scheduler fault, that for some reason didn't executed the exe correctly at logon. I've solved the issue by using Task Till Down and everything works fine now.

Using Visual basic 2017 to navigate to a esp8266 wifi switch (Sonoff)

I am using the below code to navigate to a specific web address as follows :
WebBrowser1.Navigate("http://192.168.0.157/cm?cmnd=POWER%20Toggle"
The fact is that the the link returns a .json file and the WebBrowser controls displays the default save file dialog asking if i want to save the file or run it.
I want to ignore it the dialog and read from the .json file directly(i mean after downloading it).
I just want to get rid of the Save dialog of the webbrowser.I am a newbie so i don't know what to search or how to ask properly.
Though your post is not even close to be standard and hardly explains the issue, what i understand so far is that you have a few issues and i will answer them separately.
Disabling the download dialog of the webbrowser and downloading the files automatically
Firstly, you mentioned it returns a .json file. So , you can easily add a SaveFileDialogto your form or set a custom path(maybe in a variable) and check if the webbrowser is trying to download any .json files. Then you will Cancel the call(typically i mean that cancel the popup that says Save , Run ...) and make use of the SaveFileDialog or the local variable to save the file directly to disk. Here's a sample which uses a local string variable as the path and saves the .json file directly to disk :
Imports System.ComponentModel
...
Dim filepath As String '''class lever variable
Private Sub myBroswer_Navigating(sender as Object, e As WebBrowserNavigatingEventArgs) Handles myBroswer.Navigating
If e.Url.Segments(e.Url.Segments.Length - 1).EndsWith(".json") Then
e.Cancel = True
filepath = "C:\test\" + e.Url.Segments(e.Url.Segments.Length - 1)
Dim client As WebClient = New WebClient()
AddHandler client.DownloadFileCompleted , AddressOf New AsyncCompletedEventHandler(DisplayJson);
client.DownloadFileAsync(e.Url, filepath)
End If
End Sub
Displaying the result AKA .json
It is very easy to de-serialize/parse .json files.But first, download this , extract the ZIP and Add Reference to Newtonsoft.Json.dll. Now consider the bellow code snippet :
Private Sub DisplayJson()
Dim parseJson = Newtonsoft.Json.Linq.JObject.Parse(File.ReadAllLines(filepath))
MsgBox(parseJson("element name here").ToString)
End sub
Hope this helps

Relative references when form loads in AppData folder

I've got a form that can be loaded from USB stick, from my home computer, or from work computers. The form executable is always stored in "some path\National Payroll\Build* and references a database in "some path\National Payroll".
The some path part changes, but the database is always in the parent directory. I've tried other advice to get the form's path, but I can only seem to get the path of the Local AppData folder where the form runs from when it is open, not the path of the form's executable. How do I get that?
Application.StartupPath
And, eventually Application.StartupPath.Parent
EDIT: TEST REPORT
Make a new project. Add a form with two TextBoxes named StartupPath and ExecutablePath. In the Form's Load event put the following code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
StartupPath.Text = Application.StartupPath
ExecutablePath.Text = Application.ExecutablePath
End Sub
Compile and deploy the executable on a USB flash drive (or wherever you want) and double click. This output will be produced:

How to get the path of selected folder in vb .net?

I have created a small application in vb .net to load all the files present inside the current folder where my application is running. I want to customize this application in such a manner that, when the user right click on any folder my application name also should appear in that menu. When the user click's that option, all the files present inside that corresponding folder should get listed.
I have achieved this partially. I have added my application to the right click menu item of all folders. But when I click my application name, all the files present in the parent directory is listed. I want to customize my coding to receive the path of the selected folder. So, how to do that?
There's a whole tutorial on MSDN: Verbs and File Associations
For example, the open verb normally launches a program to open a file. The command string typically looks as follows:
"My Program.exe" "%1"
You can get the parameters by the code below:
Public Sub Main(ByVal cmdArgs() As String)
If cmdArgs.Length > 0 Then
'Process the command.
'cmdArgs(0) is program name
'cmdArgs(1) is the path of your folder / file.
End If
End Sub
For Windows Forms, please see this .You'll need a function like below:
Public Sub Main(ByVal cmdArgs() As String)
'Process cmdArgs here (same as above)
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1)
End Sub

Attaching Excel File to finished Visual Basic project

I've created a Visual Basic project with many forms. In the project I write information to an excel file that I reference the location of on my local (C:) drive where the excel file resides. By reference I mean, I open an excel instance ten provide the source=local path on my hard drive. My question is how do I attach the excel file to the project so I don't have to reference the local location and can run the program on a different computer. In other words how do I bundle the excel file with the program? And how would I change the call to the excel file once I have it "bundled" to the program?
Add the excel file to the project. Go to solution explorer and right click on the excel file and select properties. Change the Copy to Output Directory to Copy Always. Now the file will be in the same directory as your exe. You can use Reflection.Assembly.GetExecutingAssembly to get the directory.
To add the file to the project:
Right click on project > Add > Existing Item > Your Excel File.xls
To include the file in build:
Right click on the file > Properties > Copy to Output Directory. Set this value to either Copy always or Copy if newer.
Here is the code to get the path to the excel file:
Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "Your Excel File.xls")
xlPath should now be the full path to the excel file.
MODIFIED REPLY AFTER USER COMMENTS
1) First create a Setting (named say MyExcelFile) to save the Name and Path of your excel file.
2) Now you can use My.Settings.MyExcelFile to refer to your excel file path.
3) If excel file is not found at the desired location, you can reset it by opening a File Open Dialog and asking the user to specify the file location.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Not IO.File.Exists(My.Settings.MyExcelFile) Then
Dim ofd As New OpenFileDialog
ofd.Filter = "Excel Files (*.xls, *.xlsx)|*.xls; *.xlsx"
ofd.Title = "Specify Excel File Location"
If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then
My.Settings.MyExcelFile = ofd.FileName
My.Settings.Save()
End If
End If
End Sub
i think iam not really getting what you mean but if you need to open the excel file with one click in the app and you dont want to write the path of the excel file (may be because you want you app portable) so the answer is to
put the excel file anywhere in the project folder
add existing item (*.* filter) and select the excel file
change the properties of the excel file build action: resource Copy to output directory:copy always
open the properties of the solution and click resources the drag the file and drop it
use the (using system.reflection & using system.io & using system.resources)
then write the code like this
string sPath = Path.GetTempFileName();
File.WriteAllBytes(sPath, Properties.Resources.excel File name here);
then take that (spath) and use it as your path so then you can change the project location with the excel file inside it and it will still be working without writing a constant path for it