Download, get the filename and execute the file - vb.net

I am posting here to ask you for help, thank you first of all for reading my message and being able to help me. :)
So here's the problem, I have a little program that I'm creating, in this one, I integrated a button that normally allows to download a tool to run it.
However the link of the file does not point directly in .exe it is a link like this one :
mydomain.com/file/file48.php
The problem is that I manage to get the file, but this one is named file48.php and gets the extension of a php file, what I would like is to get the original name of the downloaded .exe file in order to be able to execute it within my application.
Here is the current code I'm using :
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim client As New WebClient
AddHandler client.DownloadFileCompleted, AddressOf client_DownloadFileCompleted
client.DownloadFileAsync(New Uri("https ://mydomain.com/files/index.php"), fileName, filename)
End Sub
Private Sub client_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
Dim client = DirectCast(sender, WebClient)
client.Dispose()
Dim filename As String = CType(e.UserState, String)
End Sub
Thanks a lot for your help, I've been searching for hours without much success...

Related

VB.net program hangs when asked to read .txt

I am attempting to read a .txt file that I successfully wrote with a separate program, but I keep getting the program stalling (aka no input/output at all, like it had an infinite loop or something). I get the message "A", but no others.
I've seen a lot of threads on sites like this one that list all sorts of creative ways to read from a file, but every guide I have found wants me to change the code between Msgbox A and Msgbox D. None of them change the result, so I'm beginning to think that the issue is actually with how I'm pointing out the file's location. There was one code (had something to do with Dim objReader As New System.IO.TextReader(FileLoc)), but when I asked for a read of the file I got the file's address instead. That's why I suspect I'm pointing to the .txt wrong. There is one issue...
I have absolutely no idea how to do this, if what I've done is wrong.
I've attached at the end the snippet of code (with every single line of extraneous data ripped out of it).
If it matters, the location of the actual program is in the "G01-Cartography" folder.
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
MsgBox("A")
Using File As New StreamReader(FileLoc)
MsgBox("B")
Dim WholeMap = File.ReadLine()
MsgBox("C")
End Using
MsgBox("D")
End Sub
What does running this show you in the debugger? Can you open the Map_Cygnus.txt file in Notepad? Set a breakpoint on the first line and run the program to see what is going on.
Private BaseDirectory As String = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\"
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim WholeMap = File.ReadAllText(Path.Combine(BaseDirectory, "Map_Cygnus.txt"))
Debug.Print("Size Of Map: {0}", WholeMap.Length)
End Sub
It looks like you're using the correct methods/objects according to MSDN.
Your code runs for me in an new VB console app(.net 4.5)
A different approach then MSGBOXs would be to use Debug.WriteLine or Console.WriteLine.
If MSGBOX A shows but not B, then the problem is in constructing the stream reader.
Probably you are watching the application for output but the debugger(visual studio) has stopped the application on that line, with an exception. eg File not found, No Permission, using a http uri...
If MSGBOX C doesn't show then problem is probably that the file has problems being read.
Permissions?
Does it have a Line of Text?
Is the folder 'online'
If MSGBOX D shows, but nothing happens then you are doing nothing with WholeMap
See what is displayed if you rewite MsgBox("C") to Debug.WriteLine("Read " + WholeMap)
I have a few suggestions. Firstly, use Option Strict On, it will help you to avoid headaches down the road.
The code to open the file is correct. In addition to avoiding using MsgBox() to debug and instead setting breakpoints or using Debug.WriteLine(), wrap the subroutine in a Try...Catch exception.
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
Try
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
MsgBox("A")
Using File As New StreamReader(FileLoc)
MsgBox("B")
Dim WholeMap = File.ReadLine() 'dimming a variable inside a block like this means the variable only has scope while inside the block
MsgBox("C")
End Using
MsgBox("D")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Note that you normally should only catch whatever exceptions you expect, but I generally catch everything while debugging things like this.
I would also like to point out that you are only reading one line out of the file into the variable WholeMap. That variable loses scope as soon as the End Using line is hit, thereby losing the line you just read from the file. I'm assuming that you have the code in this way because it seems to be giving you trouble reading from it, but thought I would point it out anyway.
Public Class GameMain
Private WholeMap As String = ""
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
Try
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
Using File As New StreamReader(FileLoc)
WholeMap = File.ReadLine() 'dimming the variable above will give all of your subs inside class Form1 access to the contents of it (note that I've removed the Dim command here)
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

FileSystemWatcher - Cannot do this without API?

I want to check out if several folders are receieving new files and then handle that. This works fine, I have declared the FileSystemWatcher and set the EventHandler.
Now, everything works fine and if I create a new file there, it notices it.
Then, I noticed that when I paste a file, it does not notice it. I have already searched on Google and I read that it is not possible with the built-in FileSystemWatcher so far.
So I thought about API to manage this, but I have actually no idea how to deal with that or where to start. This program is one for a job, so I really need that.
I appreciate any help, links or something else to deal with that.
Thanks! if something is not clear, avoid a Downvote and ask me ;)
The following works completed as expected (.net v4.5). A paste into the directory fires the Change event.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fw As New FileSystemWatcher
fw.Path = "c:\Temp"
fw.Filter = "*.*"
fw.IncludeSubdirectories = False
AddHandler fw.Created, New FileSystemEventHandler(AddressOf FileWatcherFileChange)
AddHandler fw.Deleted, New FileSystemEventHandler(AddressOf FileWatcherFileDeleted)
AddHandler fw.Renamed, New RenamedEventHandler(AddressOf FileWatcherFileRenamed)
AddHandler fw.Error, New ErrorEventHandler(AddressOf FileWatcherError)
fw.EnableRaisingEvents = True
End Sub
Private Sub FileWatcherFileChange(ByVal source As Object, ByVal e As FileSystemEventArgs)
MsgBox("Change")
End Sub
Private Sub FileWatcherFileDeleted(ByVal source As Object, ByVal e As FileSystemEventArgs)
MsgBox("Deleted")
End Sub
Private Sub FileWatcherFileRenamed(ByVal source As Object, ByVal e As FileSystemEventArgs)
MsgBox("Renamed")
End Sub
Private Sub FileWatcherError(ByVal source As Object, ByVal e As System.IO.ErrorEventArgs)
MsgBox("Error")
End Sub
End Class
There were so many comments, I want to ensure you read this so I post as an answer. Please read this answer from me in another thread in full, including what is written on CodeProject. If what you are delivering is important work code you should really take the time to read it all.
This FileSystemWatcher class features many surprises. It is a leaky abstraction - it doesn't work in any way like it should. It might work for a while, but it always fails when conditions change.
If I were you I would ditch the FileSystemWatcher class entirely and work with time and date based scans for new files. There may be other classes and pre-made components that can help you with this.
UPDATE: New information: https://stackoverflow.com/a/23704476/129130

How to set a folder as the download location folder

I have a url link that once you click on it, a txt file automatically downloads but I want to set the folder where this txt file downloads to be in the below desktop folder "C:\Users\User1\Desktop\Folder"
The below link opens the URL in a browser and downloads the file automatically to the "Downloads" folder as I am using Chrome. I would like to set the download folder via sql vb.net.
Below are the queries I tried but only the first one worked but downloaded to "Downloads" folder (very simple):
Private Sub UpdateBtn_Click(sender As Object, e As EventArgs) Handles UpdateBtn.Click
System.Diagnostics.Process.Start("URL")
End Sub
I also tried the below code but it gave me an error that I have to specify a file name - but I don't want it to work that way:
My.Computer.Network.DownloadFile("URL", "C:\Users\User1\Desktop\Folder", "", "", False, 500, True)
Another query I tested but nothing happened:
Dim wc As New Net.WebClient
Dim Path As String = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
wc.DownloadFileAsync(New Uri("URL"), Path)
Any help would be much appreciated.
Thank you all !
Marc
If it's just a text file you could use the WebClient to download it straight from your app and then have your app write it out to the user's hard drive (wherever you have permission of course).
Dim wc As New WebClient()
AddHandler wc.DownloadStringCompleted, AddressOf wc_DownloadStringCompleted
wc.DownloadStringAsync("URL")
Private Shared Sub wc_DownloadStringCompleted(sender As Object, e As DownloadStringCompletedEventArgs)
'add any error handling code
'...
File.WriteAllText("C:\Users\User1\Desktop\Folder\MyFile.txt", e.Result)
End Sub

Pressing a button in visual basic

I am new to Visual Basic.NET and I am just playing around with it. I have a book that tells me how to read from a file but not how to write to the file with a button click. All I have is a button and a textbox named fullNameBox. When I click the button it gives me an unhandled exception error. Here is my code:
Public Class Form1
Sub outputFile()
Dim oWrite As System.IO.StreamWriter
oWrite = System.IO.File.CreateText("C:\sample.txt")
oWrite.WriteLine(fullNameBox.Text)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
outputFile()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
Have you tried stepping through your application to see where the error is? With a quick glance, it looks like you might need to use System.IO.File on the fourth line (oWrite = IO.File...) instead of just IO, but I haven't tried to run it.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SaveFileDialog1.FileName = ""
SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName.Trim.Length <> 0 Then
Dim fs As New FileStream(SaveFileDialog1.FileName.Trim, FileMode.Create)
Dim sr As New StreamWriter(fs)
sr.Write(TextBox1.Text)
fs.Flush()
sr.Close()
fs.Close()
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName.Trim.Length <> 0 Then
Dim fs As New FileStream(OpenFileDialog1.FileName.Trim, FileMode.Open)
Dim sw As New StreamReader(fs)
TextBox1.Text = sw.ReadToEnd
fs.Flush()
sw.Close()
fs.Close()
End If
End Sub
End Class
this is a complete functional program if you want, you just need to drag drop a textbox, openfiledialog, and a savefiledialog.
feel free to play around with the code.
enjoy
by the way, the problem in your code is that you "must" close filestream when your done using it, doing so will release any resource such as sockets and file handles.
The .net framework is a very powerful framework. In the same way (however) it has easy and convenient methods for simple tasks. Most individuals tend to complicate things in order to display knowledge. But less code = less processing = faster and more efficient application (sometimes) so the large above method may not be suitable. Along with that, the above mentioned method would be better off written as a sub or if returning something then a function.
My.Computer.FileSystem.WriteAllText("File As String", "TextAsString", Append as Boolean)
A general Example would be
My.Computer.FileSystem.WriteAllText("C:\text.text", "this is what I would like to add", False)
this is what I would like to add
can be changed to the current text of a field as well.
so a more specific example would be
My.Computer.FileSystem.WriteAllText("C:\text.text", fullNameBox.text, True)
If you would like to understand the append part of the code
By setting append = true you are allowing your application to write the text at the end of file, leaving the rest of the text already in the file intact.
By setting append = false you will be removing and replacing all the text in the existing file with the new text
If you don't feel like writing that part of the code (though it is small) you could create a sub to handle it, however that method would be slightly different, just for etiquette. functionality would remain similar. (Using StreamWriter)
Private Sub WriteText()
Dim objWriter As New System.IO.StreamWriter("file.txt", append as boolean)
objWriter.WriteLine(textboxname.Text)
objWriter.Close()
End Sub
The Specific Example would be
Private Sub WriteText()
Dim objWriter As New System.IO.StreamWriter("file.txt", False)
objWriter.WriteLine(fullnamebox.Text)
objWriter.Close()
End Sub
then under the button_click event call:
writetext()
You can take this a step further as well. If you would like to create a more advabced Sub to handle any textbox and file.
Lets say you plan on having multiple separate files and multiple fields for each file (though there is a MUCH cleaner more elegant method) you could create a function. {i'll explain the concept behind the function as thoroughly as possible for this example}
below is a more advanced sub demonstration for your above request
Private Sub WriteText(Filename As String, app As Boolean, text As String)
Dim objWriter As New System.IO.StreamWriter(Filename, app)
objWriter.WriteLine(text)
objWriter.Close()
End Sub
What this does is allows us to (on the same form - if you need it global we can discuss that another time, it's not much more complex at all) call the function and input the information as needed.
Sub Use -> General Sample
WriteText(Filename As String, app As Boolean)
Sub Use -> Specific Sample
WriteText("C:\text.txt, False, fullnamebox.text)
But the best part about this method is you can change that to be anything as you need it.
Let's say you have Two Buttons* and **Two Boxes you can have the button_event for the first button trigger the above code and the second button trigger a different code.
Example
WriteText("C:\text2.txt, False, halfnamebox.text)
The best part about creating your own functions and subs are Control I won't get into it, because it will be off topic, but you could check to be sure the textbox has text first before writing the file. This will protect the files integrity.
Hope this helps!
Richard Sites.

Monitor process standard output that does not necessarily use CR/LF

My application periodically starts console programs with process.start. I need to monitor the output of the programs in "realtime".
For example, the program writes the following text to the console:
Processing.................
Every second or so a new dot appears to let the user know the program is still processing. However,... until the programm outputs a CR/LF, I am not able to retrieve the standard output of the program (while it is still running).
What can I do to get the output in realtime for - let's say - piping it into a database for instance in VB.NET?
what about sending output into a text file and reading that file every second?
I'm gutted since I did have a prototype application at home that did something like this. I'll see if I can fetch it. In the meantime have a look at this link:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
It shows how to redirect the output of applications to a custom stream e.g.
Public Class Form1
Private _p As Process
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim psi As New ProcessStartInfo()
psi.FileName = "C:\mydir.bat"
psi.RedirectStandardOutput = True
psi.UseShellExecute = False
_p = New Process()
_p.Start(psi)
tmrReadConsole.Enabled = True
End Sub
Private Sub tmrReadConsole_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrReadConsole.Tick
If _p IsNot Nothing Then
txtConsoleOutput.Text = _p.StandardOutput.ReadToEnd()
End If
End Sub
End Class
The above is a webform that has a timer which is used to poll the output stream of a console and get it's content into a textbox. It doesn't quite work (hence why I want to find my other app), but you get the idea.
Hope this helps.