VB.NET How to copy the application's executable file to another path? - vb.net

I'm new to VB.NET and I'm trying to experiment with it. So when the user clicks a button from the application, the executable file should copy itself to a specific path.
So, how can I do that?
Thanks.

This is not recommended but possible - think about why in the earth you want to do that. A software is not just an EXE.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileToCopy As String
Dim NewCopy As String
FileToCopy = Application.StartupPath.ToString & "\WindowsApplication1.exe"
NewCopy = "D:\_working\WindowsApplication1.exe.copied"
If System.IO.File.Exists(FileToCopy) = True Then
System.IO.File.Copy(FileToCopy, NewCopy)
MessageBox.Show("File Copied")
End If
End Sub
End Class

The code above is flawed if you are speaking about getting your own assembly in Visual Studios to copy itself to a given path. I tested the following code and it worked without error. Please note the path will have to be changed to fit your needs and be sure to use the name of your program, mine was CryLok.exe.
Reference: https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.location?view=net-5.0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FileToCopy As String
Dim NewCopy As String
FileToCopy = Reflection.Assembly.GetExecutingAssembly().Location
NewCopy = "C:\Users\your name\Desktop\CryLok.exe"
If File.Exists(FileToCopy) = True Then
File.Copy(FileToCopy, NewCopy)
MessageBox.Show("File Copied")
End If
End Sub

Related

File.create shows no errors but doesnt create file?

I'm trying to copy a file from an external drive by reading its contents, creating a new file elsewhere and writing the contents into it. My code shows no errors (using MSV) but when I try to 'download' the file, it completes the code but no file is created.
Can anyone help?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim FileReader As String
FileReader = My.Computer.FileSystem.ReadAllText(Label32.Text)
Dim fbd As FolderBrowserDialog = New FolderBrowserDialog
Dim DownloadLocation As String
If fbd.ShowDialog() <> DialogResult.Cancel Then
DownloadLocation = fbd.SelectedPath
File.Create(fbd.SelectedPath & "pandora speedsign log.txt").Dispose()
File.WriteAllText(fbd.SelectedPath & "pandora speedsign log.txt", FileReader)
MessageBox.Show("success!!")
End If
'File.Create("C:\Users\%UserProfile%\Downloads" & DownloadFileDate & ".txt")
'File.WriteAllText("C:\Users\%USERPROFILE%\Downloads" & DownloadFileDate & ".txt", FileReader)
End Sub
I've been looking for different ways of creating the file, different ways of writing the file but nothing seems to work.
We can significantly simplify the code like this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim fbd As New FolderBrowserDialog()
If fbd.ShowDialog() <> DialogResult.Ok Then Exit Sub
Dim outputPath As String = IO.Path.Combine(fbd.SelectedPath, "pandora speedsign log.txt")
IO.File.Copy(Label32.Text, outputPath)
End Sub

how to get the accessible folder names from a drive with vb.net (Visual Studio 2012 Express)

I am trying to create a program for a friend that allows him to "sort out" and locate his files.
He has a couple of drives and many folders. What I would like to do for him is:
Have code that lists all of the active drives in a combo box. He can then select which drive he wants to search for any or just selected file types by extension.
Then he either selects "Everything" or a specific type (ie: Music)
Once a button is clicked, a list box fills with the full path to the file
Beginning this writing process, I have accomplished this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Button1.Enabled = False
Dim allDrives() As DriveInfo = DriveInfo.GetDrives()
Dim d As DriveInfo
For Each d In allDrives
If d.IsReady Then ComboBox1.Items.Add(d)
Next
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.SelectedIndex <> -1 Then
Try
For Each DName As String In My.Computer.FileSystem.GetDirectories(ComboBox1.Text, FileIO.SearchOption.SearchTopLevelOnly)
Dim LDN As Integer = Len(DName)
Dim FName As String = Strings.Mid(DName, 4, LDN - 3)
CheckedListBox1.Items.Add(FName, False)
Next
Catch ex As Exception
End Try
Else
Exit Sub
End If
End Sub
My first problem is that the GetDirectories process is getting directories I know that I do not have access to. I am trying to figure out how to prevent this. Can anyone help me.

I'm trying to create an application that works with voice commands with vb.net, I want it to work as "alexa"

I'm trying to create an application that works with voice commands with vb.net. I want it to work as "Alexa" and therefore have a keyword and then the commands, but the keyword and commands must be written by the user.
How do I add strings to the grammar without having to first pass them to the rule? (sorry for bad english i'm italian)
Here's my code so far:
Imports System.Speech
Public Class Form1
Dim WithEvents reco As New Recognition.SpeechRecognitionEngine
Dim WithEvents reco2 As New Recognition.SpeechRecognitionEngine
Dim recallWord As String
Dim c As Integer = 0
Dim comandoWord(c) As String
Dim comandoV As New Recognition.SrgsGrammar.SrgsOneOf
Dim recallV As New Recognition.SrgsGrammar.SrgsOneOf
Dim gram As New Recognition.SrgsGrammar.SrgsDocument
Dim rules As New Recognition.SrgsGrammar.SrgsRule("a")
Dim rules2 As New Recognition.SrgsGrammar.SrgsRule("b")
Dim recording As Boolean
Dim gram2 As New Recognition.SrgsGrammar.SrgsDocument
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
reco.SetInputToDefaultAudioDevice()
reco2.SetInputToDefaultAudioDevice()
End Sub
Private Sub btIns_Click(sender As Object, e As EventArgs) Handles btIns.Click
c = c + 1
ReDim comandoWord(c)
recallWord = txtRecall.Text
comandoWord(c) = txtComando.Text
Dim recallC As New Recognition.SrgsGrammar.SrgsItem(recallWord)
recallV.Items.Add(recallC)
rules.Add(recallV)
gram.Rules.Add(rules)
gram.Root = rules
reco.LoadGrammar(New Recognition.Grammar(gram))
Dim comandoC As New Recognition.SrgsGrammar.SrgsItem(comandoWord(c))
comandoV.Items.Add(comandoC)
rules2.Add(comandoV)
gram2.Rules.Add(rules2)
gram2.Root = rules2
reco2.LoadGrammar(New Recognition.Grammar(gram2))
reco.RecognizeAsync()
reco2.RecognizeAsync()
End Sub
Private Sub reco_speechRecognized(ByVal sender As Object, e As System.Speech.Recognition.RecognitionEventArgs) Handles reco.SpeechRecognized
If e.Result.Text = recallWord Then
MsgBox(e.Result.Text)
recording = True
End If
End Sub
Private Sub reco2_speechRecognized(ByVal sender As Object, e As System.Speech.Recognition.RecognitionEventArgs) Handles reco2.SpeechRecognized
If recording = True Then
If e.Result.Text = comandoWord(1) Then
MsgBox(e.Result.Text)
recording = False
End If
End If
End Sub
Private Sub reco_recognizecompleted(ByVal sender As Object, e As System.Speech.Recognition.RecognizeCompletedEventArgs) Handles reco.RecognizeCompleted
reco.RecognizeAsync()
End Sub
Private Sub reco2_recognizecompleted(ByVal sender As Object, e As System.Speech.Recognition.RecognizeCompletedEventArgs) Handles reco2.RecognizeCompleted
reco2.RecognizeAsync()
End Sub
End Class
Also, you mentioned you are Italian, so I am going to assume you are in Italy. If this is the case make this adjustment to:
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-EN")
Change to:
Thread.CurrentThread.CurrentCulture = New CultureInfo("it-IT")
If I am understanding you correctly, you are looking to create an object called "Choices" which represents a component of a phrase that can have one of several values. This is vital for speech recognition "GrammarBuilder". The following is an example of an established Grammar in VB.NET that I tested and compiled for you. I only have one command in it.If you wish to add more, do this: ("Activate Scarlett", "Run Notepad")) Just be sure you last word doesn't have a comma. I hope it will suffice.
Imports System.Globalization
Imports System.Speech
Imports System.Speech.Recognition
Imports System.Threading
Public Class Sentinal
Private WithEvents Sentinal As New SpeechRecognitionEngine
Public synth As New Synthesis.SpeechSynthesizer
Dim grammerBuilder As New DictationGrammar()
Private Sub Sentinal_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim commandChoices As New Choices
Dim grammarBuilder As New GrammarBuilder
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-EN")
commandChoices.Add(New String("Activate Scarlett")) '<add more
grammarBuilder.Append(commandChoices)
Sentinal.RequestRecognizerUpdate()
Dim gr As New Grammar(grammarBuilder)
Sentinal.LoadGrammarAsync(gr)
Sentinal.SetInputToDefaultAudioDevice()
Sentinal.RecognizeAsync()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub
Private Sub Sentinal_RecognizeCompleted(sender As Object, e As RecognizeCompletedEventArgs) Handles Sentinal.RecognizeCompleted
Sentinal.RecognizeAsync()
End Sub
Private Sub Sentinal_SpeechRecognized(sender As Object, e As SpeechRecognizedEventArgs) Handles Sentinal.SpeechRecognized
Select Case e.Result.Text
Case "Activate Scarlett"
'Place your event here
Case "Run Notepad"
'Event Here
End Select
End Sub
End Class
Choices Example
I designed Scarlett's program that you are asking about.
You can easily create a text file that holds your commands from Choices:
recEngine.LoadGrammar(New Grammar(New GrammarBuilder(New
Choices(File.ReadAllLines("C:\Users\justin.ross\source\repos\ScarlettCenturium\Scarlett
Centurium\Scarlett Centurium\Commands.txt")))))
I left the link to my repository. Just locate Form1.vb and open it. It will answer your question.
https://github.com/Rythorian77/Scarlett-Centurium-XI1/commit/6745552659f935881852151d5f880d2e6886f6cd

Visual Studio rename files on a directory with cycle for and substitute it with text from a textbox

I need help with the cycle for, when program start should rename files on selected directory but it doesn't.
This is the code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FolderBrowserDialog1.ShowDialog()
Label4.Text = FolderBrowserDialog1.SelectedPath
Dim counter = FolderBrowserDialog1.SelectedPath
Label5.Text = counter.Count
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim basedir As String = FolderBrowserDialog1.SelectedPath
For counter As Integer = 0 To Int(Label5.Text)
My.Computer.FileSystem.RenameFile(basedir, TextBox1.Text + "x")
Next
End Sub
End Class
First of all, FolderBrowserDialog1.SelectedPath returns a normal string. Calling SelectedPath.Count will not give you how many files are in the directory, but how many character the string path consists of.
Secondly, calling RenameFile(basedir, ...) won't do anything since basedir points to a single directory - not the files in the directory.
In order to get a proper file count, AND iterate through the file names you'd have to use something like Directory.GetFiles(basedir).
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FolderBrowserDialog1.ShowDialog()
Label4.Text = FolderBrowserDialog1.SelectedPath
Label5.Text = Directory.GetFiles(FolderBrowserDialog1.SelectedPath).Count
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim basedir As String = FolderBrowserDialog1.SelectedPath
Dim Files As String() = Directory.GetFiles(basedir) 'Declare an array that holds all file paths.
For counter As Integer = 0 To Files.Length - 1 'Minus one is important here, so that you won't get a "IndexOutOfRangeException".
My.Computer.FileSystem.RenameFile(Files(counter), TextBox1.Text & counter)
Next
End Sub
Files(counter) represents the file that it's currently at. If counter = 0 then Files(counter) would be the first file path in the array, and so on.
One thing I don't understand is why you give the new files the name of whatever you put in TextBox1 and an x. You are currently giving every file in that directory the exact same name (which is impossible). Could you tell me what you really are trying to rename them to?
In the mean time I replaced the x with counter. That will rename them to <whatever is in TextBox1>0, <whatever is in TextBox1>1, and so on.
One last thing, as you might have noticed I put the ampersand (&) instead of the plus sign (+) in the second parameter of RenameFile. Using the ampersand is the recommended way of concatenating strings, as the plus sign could cause exceptions in certain cases.
EDIT:
To keep the extension of the file you just have to extract it, and then add it to the new name:
For counter As Integer = 0 To Files.Length - 1
Dim FileExtension As String = Path.GetExtension(Files(counter)) 'Keeping the extension.
My.Computer.FileSystem.RenameFile(Files(counter), TextBox1.Text & counter & FileExtension)
Next

Opening listview items with a double click vb.net

I want to open items from a list view with a double click.
Imports System.IO
Imports System.Xml
Public Class cv7import
Private Sub cv7import_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim caminho As String
caminho = "C:\Documents and Settings\Software\Ambiente de trabalho\cv7import"
lstvicon.View = View.Details
lstvicon.GridLines = False
lstvicon.FullRowSelect = True
lstvicon.HideSelection = False
lstvicon.MultiSelect = True
lstvicon.Columns.Add("Nome")
lstvicon.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
Dim DI As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(caminho)
Dim files() As System.IO.FileInfo = DI.GetFiles
Dim file As System.IO.FileInfo
Dim li As ListViewItem
For Each file In files
li = lstvicon.Items.Add(file.Name)
Next
End Sub
Private Sub btnimp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnimp.Click
Dim caminho As String
caminho = "C:\Documents and Settings\Software\Ambiente de trabalho\cv7import"
Dim items() As ListViewItem = lstvicon.SelectedItems.Cast(Of ListViewItem).ToArray
Dim csv() As String = Array.ConvertAll(items, Function(lvi) String.Join(",", lvi.SubItems.Cast(Of ListViewItem.ListViewSubItem).Select(Function(si) si.Text).ToArray))
IO.File.WriteAllLines("C:\Documents and Settings\Software\Ambiente de trabalho\cv7import\teste.csv", csv)
End Class
That's the important part of the code, I was think of using onclick but I cant seem to get anywhere with it, any suggestions?
I also considered using and Open File Dialog but I dont think it can be done without the user's input of a path
I'm assuming that when you say open, you mean you want to open the associated file in the default program for that file type. In that case, you need to be storing the full path to the file in the list view. That can be accomplished via this code:
For Each file In files
li = lstvicon.Items.Add(file.Name)
li.Tag = file.FullName
Next
You will then need to add an event for the listview's double-click method. Within that event you'll want to look at the selected item and run the default program for it.
Private Sub lstvicon_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstvicon.DoubleClick
Process.Start(lstvicon.SelectedItems(0).Tag)
End Sub