How do I use My.Computer.FileSystem.CurrentDirectory with My.Computer.Network.DownloadFile? - vb.net

I am trying to use it like this:
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
My.Computer.Network.DownloadFile(
"http://magicalexample.com/multi.zip", "My.Computer.FileSystem.CurrentDirectory\multi.zip")
Process.Start("cmd", "/k jar xf multi.zip")
MsgBox("Done.")
End Sub
End Class
(note: I screwed up the formatting, it's right in VB, don't worry lol)
When I try to use the update button, it tells me that destinationFileName needs to include a file name. Do they not play well together or what?

My.Computer.FileSystem.CourrentDirectory is a variable and isn't going to be magically parsed into your string. You need to concatenate the variable with the file location:
My.Computer.Network.DownloadFile("http://magicalexample.com/multi.zip", My.Computer.FileSystem.CurrentDirectory & "\multi.zip")
Or use the Path.Combine() method to merge the directory plus filename:
My.Computer.Network.DownloadFile("http://magicalexample.com/multi.zip", Path.Combine(My.Computer.FileSystem.CurrentDirectory, "multi.zip"))
Note that your examples aren't working for various reasons. They need the http:// in front of them AND the file must exist at the source (cannot be a 404 Not Found Error). Also, the extra semi colon in the comments you posted seems to indicate that it wouldn't even be compiling so you might be running a prior version. I created a new project and as an example ran this code which worked to download the google logo from the main page.
My.Computer.Network.DownloadFile("https://www.google.com/images/srpr/logo11w.png", Path.Combine(My.Computer.FileSystem.CurrentDirectory, "logo.png"))

Related

vb.net Can an executable replace itself and how?

I want to make a simple updater for my program, but I do not want a separate executable. Is this possible?
So I check a location (ftp,http) for lets say version.txt, I compare versions. Now what? Can I overwrite my running executable and how. My program is like 4 MB ...
If it is not posible just tell me please :)
Update:
My.Computer.FileSystem.RenameFile("Test.exe", "SecondTest.exe")
My.Computer.FileSystem.CopyFile("12.exe", "Test.exe")
This seems to work. So I rename my current executable, then put the other on its place ... Am I looking for trouble here?
Ok so this works like a charm:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
My.Computer.FileSystem.RenameFile("Test.exe", "oldversion.exe")
My.Computer.FileSystem.CopyFile("newversion.exe", "Test.exe")
Process.Start("test.exe")
End
End Sub
End Class
So when test.exe runs, it renames itself to oldversion.exe then copies newversion to test.exe and starts it, then shuts down.
Now all I have to add is check for oldversion at every start and delete it if it exists.
The trick was to rename itself ...

Extract file using SevenZip

I'm trying to add a file unzipper to my application, so I googled a little and stumbled on the sevenzipsharp library that is able to extract the most common archive formats.
So I for testing I created a simple application with a windows form.
So the entered data is the file location C:\Users\jeee\Desktop\CriticalSubPrintout.rar and the extract location C:\Users\jeee\Desktop\Test Extract
I added some code, without any documentation.. not my strong side apparently..
Imports SevenZip
Public Class Archiver
Private Sub btnExtractArchive_Click(sender As Object, e As EventArgs) Handles btnExtractArchive.Click
Dim Extractor As New SevenZipExtractor(tbExtractFile.Text)
Extractor.ExtractArchive(tbExtractPath.Text)
End Sub
End Class
This causes an error when I try and run the code
Can anyone provide a sample code, or a link to a good example how-to-use SevenZipSharp? Because I searched and can't find any VB.NET samples.
Or maybe just help me figure out what I need to do.
Thanks.
You need to call SevenZipBase.SetLibraryPath with the path to 7z.dll, and make sure that you are using the correct version for your application (32- or 64-bit). e.g.
SevenZipBase.SetLibraryPath("C:\Dev\7z.dll")
Dim Extractor As New SevenZipExtractor(tbExtractFile.Text)
Extractor.ExtractArchive(tbExtractPath.Text)

How do you launch an .exe in a VB.net application who's directory varies amongst users?

I am creating an application for an Arma 3 server that directly launches the game and connects the user to a specific server. The problem that I am encountering, being the relatively new VB coder that I am, is that the Arma3battleye.exe directory (the .exe used to launch the game) may be installed in different directories depending on where the user originally installed it. I've developed the code to connect the user to the server if they've installed Arma in the normal location:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Process.Start("C:\Program Files (x86)\Steam\steamapps\common\Arma 3\arma3battleye.exe", "2 1 -noSplash -skipIntro -useBE -noPause -world=empty -connect=192.99.36.80 -port=2505 -mod=#Exile;#AlRayak;#AllInArmaTerrainPack;#CUP Units;#CUP Vehicles;#CUP Weapons;#CBA_A3;#TRYK's Multi-Play Unifrom's pack")
End Sub
However, after researching for many hours, I cannot determine how to have the program automatically determine the install directory of the arma3batteye.exe and then execute it with all of the correct start parameters included. Any solutions or pointers to help solve this problem would be greatly appreciate.
TLDR: What is the easiest way to program an application to automatically find the install directory of a given .exe and then execute it with the given parameters as I've done above?
Edit: Another thread similar to mine asks a similar question (how to view/get to the steam folder without hard coding it. They arrive at the conclusion that if you do (for winx32):
Dim strSteamInstallPath as String = My.Computer.Registry.GetValue(
"HKEY_LOCAL_MACHINE\SOFTWARE\Valve\Steam", "InstallPath", Nothing)
Or using this registry location for winx64:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Valve\Steam
and then were to create a button using Process.Start that it would allow you to ultimately view the directory. At this point I haven't discovered a way for that to translate into being able to execute the battleyearma3.exe from within that steam directory with the proper parameters. While it seems this code may be useful in arriving at the solution I'm looking for, I can only get the program to view the general steam directory at this time.
edit: Solution posted at bottom. Thanks to #VisualVincent who was really the one that allowed me to complete this. It really should be you having posted the correct answer, not me.
I would use the registry...
You add a key like HKEY_LOCAL_MACHINE\Software\Arma3\ServerPath = "..." when you install the server.
And whenever you need to start the client, you check up the path from that registry key.
So with the comments and tips you gave me (especially #VisualVincent) I managed to piece enough stuff together to solve my issue. Thanks to everyone for the help:
First I declared 2 variables. The first one (BattleyePath) goes into the registry as far as I can get it to dig. Executing this variable on its own will open the users steam directory. I then declared a second variable (BattleyePath2) which uses IO.Path.Combine get to the directory the users Arma3.exe is installed in:
Dim BattleyePath As String = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Valve\Steam", "InstallPath", Nothing)
Dim BattleyePath2 As String = IO.Path.Combine(BattleyePath, "SteamApps", "common", "Arma 3", "arma3battleye.exe")
I added a couple buttons to close the program and mute the sound:
`Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
My.Computer.Audio.Stop()
End Sub`
Finally I created the button that actually launches the game:
`Private Sub Button4_Click_1(sender As Object, e As EventArgs) Handles Button4.Click
Process.Start(BattleyePath2, "2 1 -noSplash -skipIntro -useBE -noPause -world=empty -connect=192.99.36.80 -port=2505 -mod=#Exile;#AlRayak;#AllInArmaTerrainPack;#CUP Units;#CUP Vehicles;#CUP Weapons;#CBA_A3;#TRYK's Multi-Play Unifrom's pack")
End Sub`

IO.File.Move doesn't work for files (VB.NET)

I am making a Program where you add files to an ListBox, and when you click the Install-Button it should move the files that got added to the ListBox, to an other folder. But this doesn't work, and i don't know how to fix. Here is my current Code:
Private Sub MoveFileBackgroundWorker(sender As Object, e As DoWorkEventArgs) Handles mfb.DoWork
For Each i As String In ListBox1.Items 'For each Items in ListBox1.Items, move.
IO.File.Move(i, mcpath_ & "\mods\")
Next
End Sub
Any help is really appreciated! PS: Sorry if my English isn't good, i am German :)
Move works in the following way:
IO.File.Move("C:\\myfile1.txt", "D:\\myfile2.txt")
It takes the source file as the first argument, and the target file as the second argument. In other words, the line above will move the file C:\myfile1.txt to a file named D:\myfile2.txt
So your line should be
IO.File.Move(i, IO.Path.Combine(mcpath_, "mods", IO.Path.GetFileName(i))
Which means: move file stored in i to the folder mcpath & "\mods\" with the same file name and extension
That's how i fixed it:
IO.File.Move(i, IO.Path.Combine(mcpath_.Trim, "mods", IO.Path.GetFileName(i)))
You need to add at mcpath_ .Trim!

Copy File on Modification FIleSystemWatcher, Visual Basic (VS 2012 V11)

After looking through many sites and some tutorial videos, I'm still stumped on this one. I'm finishing up a program and I need to add one last bit of functionality.
The program works this way. The user specifies a file in textbox1 and then specifies a directory in textbox2. The user sets how often they want the file to by copied in textbox3. The user hits run and the program copies the file to the new location, adding a number to the file name each time it is copied (to avoid overwrites). That all works fine, but I want the user to have the choice to either copy the file by time or when the file is modified.
How can I use the FileSystemWatcher to look for modification in the directory (given in textbox1) and then call the statement that copies the specified directory to the target destination (specified in textbox 2)?
Additional Note:
In one tutorial the FileSystemWatcher path was set up by doing this
Dim watched As String = System.IO.Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Pictures")
Dim fsw As New FileSystemWatcher(watched)
The path that the code directs to is "C:\Users[User Name]\Pictures" .
I can't find a resource online that shows what variables ".GetEnvironmentVariable" accepts or even what the variables mean. This is one of many reasons why I am having trouble with this last bit code.
GetEnvironmentVariable returns the value for the specified environment for the current process.
In the case of your example, USERPROFILE is the path to the folder for the current user. For example, on my laptop USERPROFILE is C:\Users\Tim.
The output of System.IO.Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Pictures") would be the USERPROFILE path plus "Pictures" - to continue with my example, it would be C:\Users\Tim\Pictures - which is the physical path to the My Pictures folder for my user account.
To get a list of all your environment variables, if you're curious, go to the DOS prompt and type in SET and hit return.
To answer your original question, you need to handle the FileSystemWatcher.Changed Event.
For example:
Private Shared Sub OnChanged(source As Object, e As RenamedEventArgs)
' Do your copy here
End Sub
You can hook the event handler up to your FileWatcher like this:
AddHandler fsw.Changed, AddressOf OnChanged
However, pay attention to this warning from the MSDN docs.
Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.
This is the code I used it does what I want it to.
Option Explicit On
Option Strict On
Imports System.IO
Imports Microsoft.VisualBasic ' I don't know this one, but the code worked without this.
Imports System.Security.Permissions ' I don't know the exactly what this does but the
' http://msdn.microsoft.com/ site did this, I assume it'f to allow for permission to
' watch files? The code still worked for me without this
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
Dim directoryPath As String = Path.GetDirectoryName(TextBox1.Text)
Dim varFileSystemWatcher As New FileSystemWatcher()
varFileSystemWatcher.Path = directoryPath
varFileSystemWatcher.NotifyFilter = (NotifyFilters.LastWrite)
varFileSystemWatcher.Filter = Path.GetFileName(TextBox1.Text) ' I know this
' limits what's being watched to one file, but right now this is
' what I want the program to do.
AddHandler varFileSystemWatcher.Changed, AddressOf OnChanged
varFileSystemWatcher.EnableRaisingEvents = True
End Sub
Private Sub OnChanged(source As Object, ByVal e As FileSystemEventArgs)
My.Computer.FileSystem.CopyFile(e.FullPath, TextBox2.Text & "\" & e.Name, True)
End Sub