none
Download File - webbrowser control or HttpWebRequest RRS feed

  • Question

  • I am using VB.net/Visual Studio 2015

    I am trying to automate the retrieval of some reports via the winForms webBrowser control, but when I get to the file download step, I am getting a open,save, cancel popup dialog box and I can not figure out how to click the save button. I am using the following to "click" the button that downloads the file: WebBrowser1.Document.GetElementById("Report_7269428xlsx").InvokeMember("click")

    I tried sendKeys, but that didn't work either.

    I was also trying to figure out how to use the HttpWebRequest (get request) to download the file, but I can not figure that out either. I would prefer to use the get request, because this seems the most efficient method. 

    Thank you. -ME

    Tuesday, June 6, 2017 11:25 PM

All replies

  • Hi kingelk,

    Based on your description, you want to use WebBrowser Control to download report, but you don't know how to click save button.

    You can add a SaveFileDialog control to your form, then add the following code on your WebBrowser's Navigating event, I do downloading pdf sample.

    Private Sub WebBrowser1_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles WebBrowser1.Navigating
            If e.Url.Segments(e.Url.Segments.Length - 1).EndsWith(".pdf") Then
                e.Cancel = True
                Dim filepath As String = Nothing
                SaveFileDialog1.FileName = e.Url.Segments(e.Url.Segments.Length - 1)
                If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
                    filepath = SaveFileDialog1.FileName
                    Dim client As New WebClient()
                    AddHandler client.DownloadFileCompleted, AddressOf OnDownloadComplete
                    'client.DownloadFileCompleted += New AsyncCompletedEventHandler(AddressOf client_DownloadFileCompleted)
                    client.DownloadFileAsync(e.Url, filepath)
                End If
            End If
        End Sub
    
        Private Sub OnDownloadComplete(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
            MessageBox.Show("File downloaded")
        End Sub

    About HttpWebRequest, you can refer to

    https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v=vs.110).aspx

    Dim http = DirectCast(WebRequest.Create("http://example.com"), HttpWebRequest)
            Dim response = http.GetResponse()
    
            Dim stream = response.GetResponseStream()
            Dim sr = New StreamReader(stream)
            Dim content = sr.ReadToEnd()

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Wednesday, June 7, 2017 7:25 AM
    Moderator
  • To download a file without user interaction, you can also use URLDownloadToFile

    For example :

    Dim nReturn As Integer = URLDownloadToFile(IntPtr.Zero, "http://cdn.pcwallart.com/images/tropical-island-paradise-sunset-wallpaper-2.jpg", "c:\test.jpg", 0, IntPtr.Zero)

    Declaration :

    <DllImport("Urlmon", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Unicode, EntryPoint:="URLDownloadToFileW", ExactSpelling:=True, SetLastError:=True)>
        Public Shared Function URLDownloadToFile(ByVal pCaller As IntPtr, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Integer, ByVal lpfnCB As IntPtr) As Integer
        End Function


    • Edited by Castorix31 Wednesday, June 7, 2017 7:53 AM
    Wednesday, June 7, 2017 7:52 AM
  • With both of them you can in fact not download a file. 

    With both you can get the address (Url) of the file to download. 

    To Download a file there is one simple method which had got during the time some variations for instance for Async downloading. 

    https://msdn.microsoft.com/en-us/library/system.net.webclient.downloadfile(v=vs.110).aspx


    Success
    Cor

    Wednesday, June 7, 2017 8:26 AM

  • I was also trying to figure out how to use the HttpWebRequest (get request) to download the file, but I can not figure that out either. I would prefer to use the get request, because this seems the most efficient method. 

    Thank you. -ME

    You can - it's not real obvious how but maybe this will help.

    I put a small .xlsx file on my site here:

    http://www.fls-online.net/VBNet_Forum/Book1.xlsx

    To download that using a WebRequest:

    Option Strict On Option Explicit On Option Infer Off Imports System.IO Imports System.IO.Path Imports System.Net Public Class Form1 Private Sub Form1_Load(sender As System.Object, _ e As System.EventArgs) _ Handles MyBase.Load Dim desktop As String = _ Environment.GetFolderPath(Environment.SpecialFolder.Desktop) Const url As String = _ "http://www.fls-online.net/VBNet_Forum/Book1.xlsx" DownloadFile(url, Combine(desktop, "TestThis.xlsx")) Stop End Sub Private Sub _ DownloadFile(ByVal url As String, _ ByVal localFilePath As String) Try If Not String.IsNullOrWhiteSpace(url) AndAlso _ Not String.IsNullOrWhiteSpace(localFilePath) Then Dim fi As New FileInfo(localFilePath) If fi.Exists Then fi.Delete() End If Dim request As WebRequest = WebRequest.Create(url) Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse) Using rStream As Stream = response.GetResponseStream Using ms As New MemoryStream rStream.CopyTo(ms) Dim data As Byte() = ms.ToArray() File.WriteAllBytes(fi.FullName, data) End Using End Using End Using End If Catch ex As Exception MessageBox.Show(String.Format("An error occurred:{0}{0}{1}", _ vbCrLf, ex.Message), _ "Exception Thrown", _ MessageBoxButtons.OK, _ MessageBoxIcon.Warning) End Try End Sub End Class


    You might want to use that one as a test and step through it to see what's going on.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Wednesday, June 7, 2017 11:36 AM
  • I am using VB.net/Visual Studio 2015

    I am trying to automate the retrieval of some reports via the winForms webBrowser control, but when I get to the file download step, I am getting a open,save, cancel popup dialog box and I can not figure out how to click the save button. I am using the following to "click" the button that downloads the file: WebBrowser1.Document.GetElementById("Report_7269428xlsx").InvokeMember("click")

    I tried sendKeys, but that didn't work either.

    I was also trying to figure out how to use the HttpWebRequest (get request) to download the file, but I can not figure that out either. I would prefer to use the get request, because this seems the most efficient method. 

    Thank you. -ME

    It sounds like you do not have a URL to download from, rather, the web page returns the file as a response to a partial postback occurring in the displayed web form.  So you have to automate the page to generate the download - you can't just download a URL.  Is that correct?

    If so, you may have to go back to trying to click the "OK" button on the save file dialog using Win32 API calls to get the dialog window and click the button.  There isn't a good way for us to help you more without running your code because everything will be specific to this particular website.  There might be a better solution than trying to click the button on the dialog but it all depends on exactly what the website is actually doing behind the scenes.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Wednesday, June 7, 2017 7:18 PM
    Moderator
  • ...

    Private Sub WebBrowser1_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles WebBrowser1.Navigating
            If e.Url.Segments(e.Url.Segments.Length - 1).EndsWith(".pdf") Then
                e.Cancel = True
                Dim filepath As String = Nothing
                SaveFileDialog1.FileName = e.Url.Segments(e.Url.Segments.Length - 1)
                If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
                    filepath = SaveFileDialog1.FileName
                    Dim client As New WebClient()
                    AddHandler client.DownloadFileCompleted, AddressOf OnDownloadComplete
                    'client.DownloadFileCompleted += New AsyncCompletedEventHandler(AddressOf client_DownloadFileCompleted)
                    client.DownloadFileAsync(e.Url, filepath)
                End If
            End If
        End Sub
    
        Private Sub OnDownloadComplete(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
            MessageBox.Show("File downloaded")
        End Sub

    ...


    This is one of the few ways to introduce a memory leak in a managed application.  You are creating a WebClient instance, attaching an event handler, and then allowing the instance variable to fall out of scope.  The normal cleanup process of a method falling out of scope cannot destroy the WebClient instance because a handler is still attached to it.  And you can no longer remove the handler or dispose the WebClient because you've lost any reference to it.

    The code would need to be refactored to keep the reference to the WebClient instance and clean it up after the download was completed.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Wednesday, June 7, 2017 7:22 PM
    Moderator