Webclient.DownloadFile to Folderbrowser.Selectedpath - vb.net

I want my code to download a file from a website and save it to an directory that the user has selected in the FolderBrowserDialog ... i've tried this code below without success:
' Download the files
If My.Computer.Network.IsAvailable Then
Try
wClient.DownloadFile(New Uri("DOWNLOAD LINK"), FolderBrowserDialog1.SelectedPath & "FILENAME.123")
wClient.DownloadFile(New Uri("DOWNLOAD LINK"), FolderBrowserDialog1.SelectedPath & "FileName.123)
wClient.DownloadFile(New Uri("Download LINK"), FolderBrowserDialog1.SelectedPath & "FileName.123")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

Here is some sample code I have written for you that should get you started.
first we declare wClient as a WebClient with Events so we can trigger what happens when the file downloads.I have used VLC Media Player as an example download, change to suit your needs. NOTE I did this with a button click event which you don't necessary need to do.
Imports System.ComponentModel
Imports System.Net
Public Class Form1
Private WithEvents wClient As New WebClient()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FolderBrowserDiaglog1 As New FolderBrowserDialog()
Dim folderPath As String = ""
Dim fileName As String = "vlc.exe"
Dim downloadFile As String = "https://get.videolan.org/vlc/2.2.6/win32/vlc-2.2.6-win32.exe" ''VLC MEDIA PLAYER
If FolderBrowserDiaglog1.ShowDialog() = DialogResult.OK Then
folderPath = FolderBrowserDiaglog1.SelectedPath
End If
If My.Computer.Network.IsAvailable Then
Dim combinePath As String = System.IO.Path.Combine(folderPath, fileName)
wClient.DownloadFileAsync(New Uri(downloadFile), combinePath)
End If
End Sub
Private Sub wClient_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs) Handles wClient.DownloadFileCompleted
MessageBox.Show("File Downloaded")
End Sub
End Class
Have a look in the wClient's event list and see the many options that are avalible such as the one that i have made that shows a messagebox once the file has been downloaded.
Webclient events https://msdn.microsoft.com/en-us/library/system.net.webclient_events(v=vs.110).aspx

Related

Print-to-screen log window

I have to run a process - through the execution of a batch script - which produces an output that is saved as a text file. Furthermore, I need to see this output on a form of the application of mine and, to do this, I've set an iterative timer which updates every second the content of a non-editable RichTextBox but I have two issues:
Each time the timer stops and restarts, I need to create a copy the output file, since the file is used from another process and can't be loaded onto the software as it is;
Creating and loading this text file may be honerous in terms of hardware capability, since this file may reach really big size (even more than 5 GB).
Here is the code I'm providing:
Private Sub Form9_Load(sender As Object, e As EventArgs) Handles MyBase.Load
[...]
Me.Timer1.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds
Me.Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Application.DoEvents()
Dim p = Process.GetProcessesByName("fds2ftmi_win_64")
Dim appPath As String = Path.GetDirectoryName(Application.ExecutablePath)
If My.Computer.FileSystem.FileExists(Form1.TextBox5.Text + "/HTAoutput.dat") Then
If p.Count > 0 Then
RichTextBox1.Refresh()
My.Computer.FileSystem.CopyFile(Form1.TextBox5.Text + "/HTAoutput.dat", Form1.TextBox5.Text + "/HTAoutemp.dat", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, FileIO.UICancelOption.DoNothing)
RichTextBox1.LoadFile(Form1.TextBox5.Text + "/HTAoutemp.dat", RichTextBoxStreamType.PlainText)
RichTextBox1.SelectionStart = RichTextBox1.TextLength
RichTextBox1.ScrollToCaret()
Else
Call Button3_Click(sender, e)
End If
End If
End Sub
Is there a more efficient way to show this stream-writing onto my log-window?
Thanks all are gonna answer me
EDIT 1:
Here is the code I'm providing:
Dim p = Process.GetProcessesByName("fds2ftmi_win_64")
Dim appPath As String = Path.GetDirectoryName(Application.ExecutablePath)
Dim str As FileStream
str = File.Open(Form1.TextBox5.Text + "/HTAoutput.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
If My.Computer.FileSystem.FileExists(Form1.TextBox5.Text + "/HTAoutput.dat") Then
If p.Count > 0 Then
RichTextBox1.LoadFile(str, RichTextBoxStreamType.PlainText)
RichTextBox1.SelectionStart = RichTextBox1.TextLength
RichTextBox1.ScrollToCaret()
Application.DoEvents()
Else
Call Button3_Click(sender, e)
End If
End If
Here is a simple demonstration of opening a file once and continuing to read only new data as it is added to that file.
Create a new WinForms Application project with two forms. Add a TextBox and a Button to each form. Make the TextBox multiline on Form1. Add a text file to your project named Test.txt and set Copy to Output Directory to Copy always. Add some default text to the file. Add this code to Form1:
Imports System.IO
Public Class Form1
Private reader As StreamReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Open the file for reading and allow sharing.
Dim filePath = Path.Combine(Application.StartupPath, "Test.txt")
Dim strm = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
reader = New StreamReader(strm)
'Read all available text and append to the existing text.
TextBox1.Text = reader.ReadToEnd()
Form2.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Read all available text and append to the existing text.
TextBox1.AppendText(reader.ReadToEnd())
End Sub
End Class
and add this code to Form2:
Imports System.IO
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filePath = Path.Combine(Application.StartupPath, "Test.txt")
'Write a new line of text to the file.
File.AppendAllText(filePath, Environment.NewLine & TextBox1.Text)
'Get ready for the next line of text.
TextBox1.Clear()
TextBox1.Select()
End Sub
End Class
Run the project and you'll see your default text in Form1. Enter some text into Form2 and click the Button. Do that a few times. Now click the Button on Form1. Voila! Repeat that cycle and see the text you enter on one form magically appear on the other.
Now go back and examine the code more closely. You can see that Form2 appends a line of code to the file each time you click the Button. Form1 reads the initial contents of the file when it loads and displays that, but it keeps the file open. Each time you click the Button, it will read only the new data, i.e. only the data after where it previously read up to. It then appends that new text to the existing text in the TextBox.

Async Download file updating the gui

I am downloading a file using webclient handling DownloadProgressChanged and DownloadFileCompleted.
My code is working whenever I am not updating the gui with percentage,b but In case I am going to update just a single label with it, then it kind of freezing in random situations. Doesn't matter if the file is little or big.
Public WithEvents mclient As New WebClient
Private Sub Download()
Dim filepath As String = (filepath..)
mclient.Encoding = Encoding.UTF8
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
mclient.Headers.Add(HttpRequestHeader.UserAgent, "")
mclient.DownloadFileAsync(New Uri(link), filepath)
End Sub
Private Sub mClient_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles mclient.DownloadProgressChanged
Try
'file website missing Content-Length, so getting the real size parsing html (real size=label7)
label1.text= ((e.BytesReceived) / 1048576).ToString("0.00") & "/" & Label7.Text
Catch ex As Exception
End Try
End Sub
Private Sub mClient_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs) Handles mclient.DownloadFileCompleted
Try
label2.text="Download ended"
Catch ex As Exception
End Try
End Sub
How can I keep label1.text updated without using it inside of DownloadProgressChanged?
If I use a variable on it, where can I keep it updated? I don't want to use a timer though..

DownloadCompleteEvent fires twice

I have a windows form which lets the user select a file name and download it, Once the download is complete, a download finished event is triggered which unzips the downloaded file and processes it further.
The downloadComplete event seems to be triggered twice which is causing the unzipping action to happen twice. Is there a reason why the event would be fired twice?
below is the function which triggers the download and Handles the download complete event.
Private Async Sub Btn_download_Click(sender As Object, e As EventArgs) Handles Btn_download.Click
Dim fileNameRows As DataGridViewSelectedRowCollection = datagridview_cloudContent.SelectedRows
Dim fileName As String
Dim fileType As String = AWSGlobals.CONTENT
For Each fileNameRow As DataGridViewRow In fileNameRows
fileName = fileNameRow.Cells(0).Value.ToString() & ".zip"
Try
Await DownloadAsyncFile(fileName, fileType)
Catch ex As Exception
CSMessageBox.ShowError("Content Import failed : ", ex)
End Try
Next
End Sub
Private Function UnzipAndImport(filename As String) Handles s3obj.DownloadDone
If Not System.IO.Directory.Exists(AWSGlobals.ContentPath & Path.GetFileNameWithoutExtension(filename)) Then
Dim zipFilePath As String = DiskPath & filename
Dim zipFileArchive As ZipArchive = ZipFile.OpenRead(zipFilePath)
Dim FullPathOfContent As String = DiskPath
ExtractToDirectoryOverWrite(zipFileArchive, FullPathOfContent, True)
ImportExport.BatchImportContent(New ArrayList(New String() {ExtractedPath}), objmanager)
End If
End Function
In the class that handles the downloads, the download method is implemented as below :
Public Function DownloadAsyncFile(FileName As String, FileType As String)
Try
Dim Address As String
AddHandler fileReader.DownloadFileCompleted, Sub(sender, e) download_complete(FileName)
AddHandler fileReader.DownloadProgressChanged, AddressOf Download_ProgressChanged
fileReader.DownloadFileAsync(New Uri(Address), AWSGlobals.ContentPath + FileName)
Catch ex As Exception
MsgBox( ex.Message)
End Try
End If
End Function
Private Sub download_complete(filename As String)
RaiseEvent DownloadDone(filename)
End Sub
Can someone tell me if this implementation causes the download complete event to fire twice when just one file is being downloaded?

Import CSV file to database using VB

I need to import the information from a CSV txt file to a database using the DataGridView in my form. The application should allow the user to open a .txt file and then update the DataGridView table in my form. I am able to get the file, but am unable to update the grid using the file. I can update textboxes, but cannot figure out how to update the grid. Can anyone help me out with this?
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Public Class Form1
Private fileToOpen As String 'the file to be opened and read
Private responseFileDialog As DialogResult 'response from OpenFileDialog
Private myStreamReader As StreamReader 'the reader object to get contents of file
Private myStreamWriter As StreamWriter 'the writer object to save contents of textbox
Private myTextFieldParser As TextFieldParser ' To parse text to searched.
Dim myDataAdapter As OleDb.OleDbDataAdapter
Dim myString() As String
Dim myRow As DataRow
Private Sub PeopleBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles PeopleBindingNavigatorSaveItem.Click
Me.Validate()
Me.PeopleBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.MyContactsDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyContactsDataSet.People' table. You can move, or remove it, as needed.
Me.PeopleTableAdapter.Fill(Me.MyContactsDataSet.People)
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim fileContentString As String 'contents of the file
Dim update As New OleDb.OleDbCommandBuilder(myDataAdapter)
'Dim myRow As DataRow
'set the properties of the OpenFileDialog object
OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.CurrentDirectory
OpenFileDialog1.Title = "Select File to View..."
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
'responseFileDialog contains holds the response of the user (which button they selected)
responseFileDialog = OpenFileDialog1.ShowDialog()
'check to see if the user select OKAY, if not they selected CANCEL so don't open anything
If (responseFileDialog <> System.Windows.Forms.DialogResult.Cancel) Then
'make sure there isn't a file already open, if there is then close it
If (myStreamReader IsNot Nothing) Then
myStreamReader.Close()
'TextBoxFileOutput.Clear()
End If
'open the file and read its text and display in the textbox
fileToOpen = OpenFileDialog1.FileName
myStreamReader = New StreamReader(OpenFileDialog1.FileName)
initTextFieldParser()
'loop through the file reading its text and adding it to the textbox on the form
Do Until myStreamReader.Peek = -1
fileContentString = myStreamReader.ReadLine()
'Try
' myTextFieldParser = New TextFieldParser(fileToOpen)
' myTextFieldParser.TextFieldType = FieldType.Delimited
' myTextFieldParser.SetDelimiters(",")
'Catch ex As Exception
' MessageBox.Show("Cannot Open File to Be Read!")
'End Try
myTextFieldParser.TextFieldType = FieldType.Delimited
myString = TextFieldParser.NewLine()
myRow.Item("FirstName") = myString(1)
MyContactsDataSet.Tables("People").Rows.Add(myRow)
PeopleTableAdapter.Update(MyContactsDataSet)
'TextBoxFileOutput.AppendText(fileContentString)
'TextBoxFileOutput.AppendText(Environment.NewLine)
Loop
'close the StreamReader now that we are done with it
myStreamReader.Close()
'SaveToolStripMenuItem.Enabled = True
End If
End Sub
Private Sub initTextFieldParser()
'Close myTextFieldParser in case the user is surfing through the records and then
'decides to search for a particular last name --> Basically start searching from beginning of the file
If (myTextFieldParser IsNot Nothing) Then
myTextFieldParser.Close()
End If
Try
myTextFieldParser = New TextFieldParser(fileToOpen)
myTextFieldParser.TextFieldType = FieldType.Delimited
myTextFieldParser.SetDelimiters(",")
Catch ex As Exception
MessageBox.Show("Cannot Open File to Be Read!")
End Try
End Sub
End Class
updating gridview with your file content
Import System.IO as we gonna need StreamReader
Using reader As New StreamReader("filepath")
DataGridView1.Columns.Add("col1",reader.ReadToEnd())
End Using
check this out!

how to get captcha image if src use java function?

How can I scrape captcha from this website
captchaImage.
I tried MSHTML but this website uses java script function to display retrieve captcha in it's src. Please try and answer me how can I achieve this.
Imports MahApps.Metro.Controls
Imports System.Net
Imports System.Windows.Forms
Class MainWindow
Inherits MetroWindow
Private Sub MetroWindow_Loaded(sender As Object, e As RoutedEventArgs)
wb.Navigate("https://www.irctc.co.in/eticketing/loginHome.jsf")
AddHandler wb.LoadCompleted, AddressOf wb_Loaded
End Sub
Private Sub btngo_Click(sender As Object, e As RoutedEventArgs) Handles btngo.Click
Dim htmldoc As MSHTML.IHTMLDocument2 = wb.Document
Dim usrtxtdoc As MSHTML.IHTMLElement = htmldoc.all.item("j_username", 0)
Dim usrpwddoc As MSHTML.IHTMLElement = htmldoc.all.item("j_password", 0)
Dim captchadoc As MSHTML.IHTMLElement = htmldoc.all.item("j_captcha", 0)
usrtxtdoc.innerText = txtusrname.Text
usrpwddoc.innerText = txtpwd.Text
captchadoc.innerText = txtcaptcha.Text
End Sub
Private Sub wb_Loaded(sender As Object, e As System.Windows.Navigation.NavigationEventArgs)
MsgBox("Loaded")
Dim htmldoc As MSHTML.IHTMLDocument2 = wb.Document
Dim htmldoc2 As MSHTML.HTMLDocument = wb.Document
Dim captchaimg As MSHTML.HTMLImg = htmldoc.all.item("cimage", 0)
Dim bitmap As New BitmapImage
bitmap.BeginInit()
bitmap.UriSource = New Uri(wb.FindResource("captchaImage"))
bitmap.EndInit()
imgcaptcha.Source = bitmap
End Sub
Private Sub wb_Navigated(sender As Object, e As NavigationEventArgs) Handles wb.Navigated
lblwbstatus.Content = "Load Completed"
End Sub
Private Sub wb_Navigating(sender As Object, e As NavigatingCancelEventArgs) Handles wb.Navigating
lblwbstatus.Content = "Navigating Please wait"
End Sub
Private Sub lblwbstatus_MouseDoubleClick(sender As Object, e As MouseButtonEventArgs) Handles lblwbstatus.MouseDoubleClick
wb.Refresh()
End Sub
End Class
you can download source from this link
Normally you would do this:
Dim htmldoc As mshtml.IHTMLDocument2 = wb.Document.DomDocument
Dim captchaimg As mshtml.HTMLImg = htmldoc.all.item("cimage", 0)
Dim imgRange As IHTMLControlRange = htmldoc.body.createControlRange()
For Each img As IHTMLImgElement In htmldoc.images
If img.nameProp = "captchaImage" Then
imgRange.add(img)
imgRange.execCommand("Copy", False, Nothing)
Using bmp As Bitmap = Clipboard.GetDataObject().GetData(DataFormats.Bitmap)
bmp.Save("c:\test.bmp")
End Using
End If
Next
However the image has an alpha channel that doesn't get copied to clipboard because of internet explorer issues (as you can read here Copying image from page results in black image).
Other ways are to check on internet explorer cache, but that image won't be cached because of HTTP headers, so you are out of luck.
the code above work very good with consideration -to the:
1- Item type- as in your webpage target example ("IMG").
2- the image proper name example: CaptchaImg.jpg to be written as CaptchaImg.jpg
3- add reference to (mshtml) and Imports mshtml into your project
4- right-Click reference on your project --> click add reference -->
-->Browse button click -choose or navigate to --->
C:\Windows\assembly\GAC\Microsoft.mshtml\7.0.3300.0__b03f5f7f11d50a3a\Microsoft.mshtml.dll
----> ok button click --- this will add Microsoft.mshtml.dll to your reference
finallt import to your project as (Imports mshtml).
5- change the directory bmp.Save("c:\test.bmp")---> to for example bmp.Save("c:\test\test.bmp")
for security and administration right privileged.