How to get the path of selected folder in vb .net? - 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

Related

How to tell if Folder is opened in explorer

I'm writing a script in Siemens NX using vb.net, which helps export drawing files. The file will be exported into a folder, that is kind of bothersome to manually navigate to, so I want to open said folder up to the user after the export.
The target folder is in a plm safe, so the file needs to be checked in in order to be used by other people.
Process.Start(targetfolder) doesn't work, because the folder gets opened "dumb" without any of the plm safe functionality.
Process.Start("explorer.exe", targetfolder) opens the folder using the proper safe environment, however it will open a second folder when I run it again. Ideally I would like the folder to only become active if it's already opened.
I found that I could use
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
Private Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
End Function
...
If FindWindow(vbNullString, IO.Path.GetFileName(targetfolder)) = 0 Then
Process.Start("explorer.exe", targetfolder)
Else
AppActivate(IO.Path.GetFileName(targetfolder))
End If
In order to only open a new window if there isn't one already. However, this also doesn't work reliably, because IO.Path.GetFileName(targetfolder) returns only the folder's name without the entire path. This means that if the user has a folder opened, that has the same name as the target folder but sits in a different spot FindWindow(vbNullString, IO.Path.GetFileName(targetfolder)) will find the other folder to be opened and won't open the target folder. It essentially can't differentiate the two. Additionally, AppActivate(IO.Path.GetFileName(targetfolder)) doesn't work if there are two folders of the same name opened.
Another thing I found was that you cannot rename a directory using FileSystem.Rename() while a child folder of the target folder is opened. I could use this to check if the target folder is opened, by trying to rename the parent folder, however this will create many many false positives.
I am now officially out of ideas. I also cannot use the plm safe's API, because the NX-script doesn't allow the use of "foreign" dll files, such as the plm library.
How do I check if a specific path is already opened in an explorer window?
Taken from here, you could do something along those lines:
Private Function isPathOpenedInExplorer(myPath As String) As Boolean
Dim shellWindows As SHDocVw.ShellWindows = New SHDocVw.ShellWindows()
Dim filename As String
For Each ie As SHDocVw.InternetExplorer In shellWindows
filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower()
If filename.Equals("explorer") Then
If myPath = ie.LocationURL.Remove(0, 8).Replace("/", "\").Replace("%20", " ") Then
Return True ' Found
End If
End If
Next
Return False 'Not Found
End Function
don't forget to Imports System.IO and Add reference to 'SHDocVw'

Open a .exe that is in project folder

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)

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

Visual Basic 6.0 FileListBox

How do I show only specific file types in the file list box? For example, show all .docx files from the whole computer directories. I would also want people to choose from the files listed in the "File list box" and open it through a command button.
The FileListBox has "Pattern" property. Enter *.docx there.
Also: add a DirListBox and a DriveListBox too.
Private Sub Drive1_Change()
Dir1.Path=Drive1.Drive
End Sub
Private Sub Dir1_Change()
File1.Path=Dir1.Path
End Sub

Releasing memory held in objects in VB.NET

I am using a 3rd party DLL from pdf-tools to parse PDF files inside my VB.NET application and write the extracted data to a SQL localDB database. I'm giving the user two options: to select a PDF file for parsing or to point to a folder and the application will loop through all PDF files inside it. Both options call the same procedure doPDFFile() as below.
The problem is: if I import a number of files individually by selecting a file every time, the program runs fine. However, If I select a folder that contains the same files, the memory used by the program will keep growing further and further. In Windows task manager, it can reach to 1 GB after importing around 30 files.
I used ANTS memory profiler from redgate, and it showed that one object called "GraphicsState" which is part of the pdf-tools object is growing too big when looping inside a folder. This does not happen if I select the same files one by one. Besides the memory problem, the application becomes very slow after parsing some files. My questions is: why is this happening? and how to prevent it? The user should be able to point the program to a folder with hundreds of PDF files, how can I achieve this?
Below is a snapshot of the code:
'When user selects one file
Private Sub OpenToolStripMenuItem_Click(...)
OpenFileDialog1.FileName.ToString
doPDFFile()
End Sub
'When user selects a folder
Private Sub LoopToolStripMenuItem_Click() Handles LoopToolStripMenuItem.Click
FolderBrowserDialog1.ShowDialog()
sPath = FolderBrowserDialog1.SelectedPath
For Each fileName As String In IO.Directory.GetFiles(...)
sPath = fileName
doPDFFile()
Next
End Sub
Inside the doPDFFile() procedure, I'm doing the following, I'm using the document object from pdf-tools and I'm passing it byRef to another procedure:
Public Sub doPDFFile()
Using document As New Pdftools.PdfExtract.Document
document.open(sPath)
findFirstPage(document) 'passing by reference
ParseFirstPage(document) 'passing by reference
'storing the parsed text in an array
'.......
do
'extracting the colors from the graphicsStateObject inside the document object:
Using objGraphicsState As Pdftools.PdfExtract.GraphicsState = content.GraphicsState
sColor = objGraphicsState.FillColorRGB
End Using
'save text and color in an array of objects
until endOfText
end using
end sub